There are multiple directories which contain a file with the same name:
direct_afaap/file.txt direct_fgrdw/file.txt direct_sardf/file.txt ...
Now I want to extract them to another directory, direct_new
and with a different file name such as:
[mylinux~ ]$ ls direct_new/ file_1.txt file_2.txt file_3.txt
How can I do this?
BTW, if I want to put part of the name in original directory into the file name such as:
[mylinux~ ]$ ls direct_new/ file_afaap.txt file_fgrdw.txt file_sardf.txt
What can I do?
Advertisement
Answer
This little BaSH script will do it both ways:
#!/bin/sh # # counter i=0 # put your new directory here # can't be similar to dir_*, otherwise bash will # expand it too mkdir newdir for file in `ls dir_*/*`; do # gets only the name of the file, without directory fname=`basename $file` # gets just the file name, without extension name=${fname%.*} # gets just the extention ext=${fname#*.} # get the directory name dir=`dirname $file` # get the directory suffix suffix=${dir#*_} # rename the file using counter fname_counter="${name}_$((i=$i+1)).$ext" # rename the file using dir suffic fname_suffix="${name}_$suffix.$ext" # copy files using both methods, you pick yours cp $file "newdir/$fname_counter" cp $file "newdir/$fname_suffix" done
And the output:
$ ls -R cp.sh* dir_asdf/ dir_ljklj/ dir_qwvas/ newdir/ out ./dir_asdf: file.txt ./dir_ljklj: file.txt ./dir_qwvas: file.txt ./newdir: file_1.txt file_2.txt file_3.txt file_asdf.txt file_ljklj.txt file_qwvas.txt