1

i know this would be marked as a duplicate one, but i tried searching google and what i'm trying is not working for me.

I've some .txt files in a directory, i need to rename all the *.txt files to *_XYZ.txt recursively. XYZ is defined in a variable X.

I've tried below code:

file=`find ./ -type f -name "*.txt"|sed "s,^./,,g" |awk -F '.' '{print $1}'`

for i in "$file"
do
mv "$i" "$i_${X}.txt"
done

Any help would be greatly appreciated. Thanks.

User123
  • 1,498
  • 2
  • 12
  • 26

1 Answers1

1

Your script destroys original filenames in variable file, this is why it cannot rename files.

Working example:

X="_XYZ"
for f in $(find . -type f ! -name "*$X.txt" -name "*.txt"); do 
    mv "$f" "${f%.txt}$X.txt"
done

Output:

$ X="_XYZ"
$ find . -type f -name "*.txt"
./c_XYZ.txt
./aa/c.txt
./a.txt
./b.txt
$ for f in $(find . -type f ! -name "*$X.txt" -name "*.txt"); do mv "$f" "${f%.txt}$X.txt"; done
$ find . -type f -name "*.txt"
./b_XYZ.txt
./c_XYZ.txt
./aa/c_XYZ.txt
./a_XYZ.txt
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • Thanks @Maxim:-) .It worked. i was just messed up in the `mv` part.can you please elaborate the command please. – User123 Jun 20 '18 at 10:09
  • 1
    @User123 `${f%.txt}` chops off trailing `.txt` from variable `f`. See https://www.tldp.org/LDP/abs/html/parameter-substitution.html for more details. – Maxim Egorushkin Jun 20 '18 at 10:11