2

How can I append characters to a files name in linux, using a regex? I've seen these two posts

  1. https://stackoverflow.com/questions/6985873/change-names-of-multiple-files-linux
  2. How to rename multiple files by replacing word in file name?

but haven't been able to get the answers to work for me. I'm also not sure if this belongs here, stack overflow or in another sub-site.

I've been trying

for FILE in \d+_\d+\.png; do echo "$FILE" $(echo "$FILE" | sed 's/\./_t\./'); done

but that doesn't seem to recognize the regexed filename as a regex.

So for data samples my files currently are

1111_2222.png

and I want them to be

1111_2222_t.png

The files are scattered amongst five directories. Thanks.

3 Answers3

3
[vagrant@vm-one ~]$ ls
1111_2222.png  1111_4444.png  1111_6666.png
[vagrant@vm-one ~]$ for f in `ls | egrep '[0-9]+_[0-9]+\.png'`; do mv "$f" "${f/.png/_t.png}"; done
[vagrant@vm-one ~]$ ls
1111_2222_t.png  1111_4444_t.png  1111_6666_t.png

Sources

  1. The ls | egrep snippet has been retrieved from here

  2. The mv $f ${f/.png/_t.png} based on this answer

030
  • 6,085
2

This works for me in my test..

shopt -s globstar; 
for i in **; do
    test -f ${i} || continue;
    ext=${i##*.};
    echo mv $i ${i%%.${ext}}_t.${ext}; 
done;
shopt -u globstar;

It expects you to be in the correct base directory. Note it makes no assumptions as to what extension the file is or what the 'start' of the filename format is. Be careful.

Matthew Ife
  • 24,261
0

Simple (maybe too much), but also works in this case:

find . -regextype posix-extended \
  -regex '.*[[:digit:]]{4}_[[:digit:]]{4}\.png' \
  -type f -exec rename .png _t.png {} \;
dawud
  • 15,504