0

I have a large number of files in directories of the format */*/*/*/*.txt and I would like to copy them into a different place while replacing the forward-slashes in the path with underscores. For example, if a file is located at A/B/C/D/E.txt, I'd like to copy it to dest/ so that its path after copying is dest/A_B_C_D_E.txt. Is this possible?

0

You can use script like this:

for i in `find . -type f -name "*.txt"`
do
newfile=$(echo $i|sed -s 's@/@_@g'|cut -c -3)
mv "$i" "dest/$newfile"
done

If the number of files if very big you can try with while instead of for

while read i
do 
    newfile=$(echo $i|sed -s 's@/@_@g'|cut -c -3)
    mv "$i" "dest/$newfile"
done < (find . -type f -name "*.txt")

P.S. Be warned about the filenames/directories with nonstandard symbols in filenames. For reference check this question and answers

  • 3
    This will break on a bunch of filenames. – jordanm Jan 16 at 6:58
  • @jordanm, can you please clarify? – Romeo Ninov Jan 16 at 6:59
  • 2
    @RomeoNinov Anything with spaces, for example, but also files with globbing patterns. See e.g. unix.stackexchange.com/questions/321697 – Kusalananda Jan 16 at 7:15
  • 2
    @RomeoNinov Note that an answer is never an answer to a single user and their specific setup. An answer may be read years from now and applied to a setup where files may well have spaces and strange characters in their filenames. – Kusalananda Jan 16 at 7:24
  • 1
    I was able to fix the leading ._ problem by adding to the newfile line: newfile=$(echo $i|sed -s 's@/@_@g'|cut -c -3) – David Scott Jan 17 at 2:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.