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?

Danica Scott
  • 143
  • 1
  • 4

1 Answers1

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

Romeo Ninov
  • 16,541
  • 5
  • 32
  • 44
  • 3
    This will break on a bunch of filenames. – jordanm Jan 16 '19 at 06:58
  • @jordanm, can you please clarify? – Romeo Ninov Jan 16 '19 at 06:59
  • 2
    @RomeoNinov Anything with spaces, for example, but also files with globbing patterns. See e.g. https://unix.stackexchange.com/questions/321697 – Kusalananda Jan 16 '19 at 07:15
  • @Kusalananda, I agree with most of the things. But let give to OP the opportunity to check if he have such odd filenames/directories :) – Romeo Ninov Jan 16 '19 at 07:19
  • 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 '19 at 07:24
  • I noticed that this includes the leading `./` in the path, so this results in filenames starting with `._`, which isn't ideal – Danica Scott Jan 17 '19 at 02:09
  • I don't have any odd filenames, so this works for me. However I am hesitant to mark it as an answer because it isn't completely generic – Danica Scott Jan 17 '19 at 02:12
  • 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)` – Danica Scott Jan 17 '19 at 02:20
  • @DavidScott, will add it in to the answer – Romeo Ninov Jan 17 '19 at 05:23