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.

  • One thing is you lost `mv` command. It should read `do mv`. – baf Apr 03 '15 at 19:27
  • I want to see the changes before I execute them, just incase I'm doing something stupid. – user3783243 Apr 03 '15 at 19:31
  • Sure. In bash this should work `for FILE in [0-9]*_[0-9]*.png`. Plus `+` will not work. – baf Apr 03 '15 at 19:36
  • @baf `+` works, `\d` doesn't. `+` and `*` are quite different, `*` will allow the value not be present, `+` requires at least one occurrence of the value. – user3783243 Apr 06 '15 at 14:55
  • I know the difference between `+` and `*`, but plus doesn't work for simple bash expansion. It will work for grep regex, but not in pure bash. See [bash glob patterns](http://mywiki.wooledge.org/BashGuide/Patterns). Anyway I think your script with my tweaks is the simplest solution, no need for grep and other stuff :) – baf Apr 06 '15 at 19:50

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
  • 5,731
  • 12
  • 61
  • 107
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
  • 22,927
  • 2
  • 54
  • 71
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
  • 14,918
  • 3
  • 41
  • 61