Извлечение всех имен изображений с именами вложенных папок в CSV файл с помощью сценария оболочки

Ваш неверное имя переменной :)

Чтобы проблема исчезла, заключите переменную в двойные кавычки.

export srcfileTimeCheck="$(find "$dir" -type f -mtime +1)"
4
08.02.2017, 11:58
4 ответа

Попробуйте следующее:

find ~/Desktop -iname "*.jpg" -exec ls {} + | awk -F'/' ' BEGIN { OFS=", "; print "Image Name", "Category", "Subcategory", "type"} { print $(NF-1),$4, $5, $3 "" }' 

Если вы хотите удалить специальный символ из имени изображения, используйте приведенный ниже код:

find ~/Desktop -iname "*.jpg" -exec rename 's/[^a-zA-Z0-9.\/-]//g' {} +

Настройте его в соответствии с выход.

1
27.01.2020, 20:53

Просто потому, что мы можем, вот способ, который использует sed для изменения порядка полей:

find -name "*.jpg" | sed -rn 's|^.||; s|[^/]*.jpg||; :a h; s|.*/(.*)|\1|p; x; s|(.*)/.*|\1| ; ta' | tr '\n' ',' | sed 's/,,/\n/g ; s/,$/\n/; s/^,//'

Да, я знаю O_O

Но он работает, даже если структура каталогов несовместима

Здесь более читабельно с комментариями:

find -name "*.jpg" | sed -rn '{    #get the files and pipe the output to sed
s|^.||                             #remove the leading .
s|[^/]*.jpg||                      #and the basename, since each image is in a directory of the same name
:a h                               #create a label a for this branch and put the lines into the hold space in their current state
s|.*/(.*)|\1|p                     #print only the last field
x                                  #switch the hold space and pattern space 
s|(.*)/.*|\1|                      #exclude the last field from the new pattern space, which won't do anything if there is only one field on each line
ta                                 #if the last s command did anything, then start again from the label (:a) (thus recursively going through the fields and printing them out on separate lines in reverse order)
}' | tr '\n' ',' | sed '{          # finally turn the newlines into commas, then clean up the mess
s/,,/\n/g ; s/,$/\n/; s/^,//
}'
2
27.01.2020, 20:53

попробуйте эту команду ..

find . | awk -F/ '{print $(NF-1)","$(NF-3)","$(NF-2)","$(NF-4)}'
1
27.01.2020, 20:53

Предполагая, что у вас есть согласованная древовидная структура каталогов, сценарий python, представленный ниже будет перемещаться по дереву каталогов и выводить содержимое csv в поток stdout (используйте оператор > в командной строке для вывода содержимого в новый файл, как в ./ dir_tree_csv.py> output_file.csv ). Он должен быть помещен в каталог Wall Arts Product Images и выполнен оттуда.

#!/usr/bin/env python
from __future__ import print_function
import os,sys

def get_all_files(treeroot):
    file_list = []
    for dir,subdirs,files in os.walk(treeroot):
         for f in files: 
             if os.path.basename(__file__) in f: continue
             file_list.append(os.path.join(dir,f))
    return file_list

def main():
    top_dir="."
    if len(sys.argv) == 2: top_dir=sys.argv[1]
    files = get_all_files(top_dir)

    print("Image name,category,subcategory,type\n")

    for f in files:
        fields = f.split('/')
        fields.reverse()
        fields[2],fields[3] = fields[3],fields[2]
        print(",".join(fields[1:-1]))

if __name__ == '__main__' : main()

Пробный запуск:

# Replicated directory structure with only two of the files for simplicity
 $ tree
.
├── dir_tree_csv.py
├── framed-posters
│   └── landscape
│       └── animals-and-birds
│           └── Bighorn
│               └── Bighorn.jpg
└── posters
    └── landscape
        └── Automobiles
            └── Best-Deisgner-Jack-Daniel-Chopper
                └── Best-Deisgner-Jack-Daniel-Chopper.jpg

8 directories, 3 files
$ ./dir_tree_csv.py                                                                                   
Image name,category,subcategory,type

Best-Deisgner-Jack-Daniel-Chopper,landscape,Automobiles,posters
Bighorn,landscape,animals-and-birds,framed-posters
1
27.01.2020, 20:53

Теги

Похожие вопросы