Copying files from multiple directories into a single destination directory

前端 未结 4 2004
挽巷
挽巷 2021-01-24 09:14

There are multiple directories which contain a file with the same name:

direct_afaap/file.txt
direct_fgrdw/file.txt
direct_sardf/file.txt
...

N

4条回答
  •  醉梦人生
    2021-01-24 09:47

    You can achieve this with Bash parameter expansion:

    dest_dir=direct_new
    
    # dir based naming
    for file in direct_*/file.txt; do
      [[ -f "$file" ]] || continue # skip if not a regular file
      dir="${file%/*}"             # get the dir name from path
      cp "$file" "$dest_dir/file_${dir#*direct_}.txt"
    done
    
    # count based naming
    counter=0
    for file in direct_*/file.txt; do
      [[ -f "$file" ]] || continue # skip if not a regular file
      cp "$file" "$dest_dir/file_$((++counter)).txt"
    done
    
    • dir="${file%/*}" removes all characters starting from /, basically, giving us the dirname
    • ${dir#*direct_} removes the direct_ prefix from dirname
    • ((++counter)) uses Bash arithmetic expression to pre-increment the counter

    See also:

    • Why you shouldn't parse the output of ls(1)
    • Get file directory path from file path
    • How to use double or single brackets, parentheses, curly braces

提交回复
热议问题