1

How to improve the command below to change a string in a filename.

find . -type f -name '*<today>*' -exec mv {} {}_renamed \;

Actually I have a few files in my directory with today's date as a part of the name. I want to change the names of all the files such that only the date string in the file name will be changed to yesterday's date from today's date.

I do not want to put a suffix or prefix to file name instead manipulate the file name.

e.g.
before command file name is xxx20170821yyyy.ppp
after command file name will be xxx20170820yyyy.ppp

and repeat this for all the files which has 20170821 string in theirname.

αғsнιη
  • 41,407
BreakBadSP
  • 113
  • 4
  • 1
    Have a look at rename. You don't even need find then (unless your files are spread over nested directories. If you don't succeed with rename tell us what you tried. – Philippos Sep 19 '17 at 10:49

1 Answers1

3

Use rename as part of Perl commands.

find . -type f -name '*20170919*' -execdir 
rename -n 's/20170919/20170918/' '{}' \;

Use execdir as it's performing its part command to be run for file found in their relative path where execdir returns. This swill prevent passing full path of file (relative to current working directory) and avoid a folder with same pattern to be renaming wrong instead of file name itself.

If all your files are in single directory, below one liner rename is enough.

rename -n 's/20170919/20170918/' *20170919*

Remove -n when you trust the rename result to have actual rename. You may need to add -v to see what being renaming.

At the end, you may need to have today's date if you want this perform everyday for bunch of files. then use date command as following in $(...) (command substitution) between double quotes.

find . -type f -name "*$(date +"%Y%m%d")*" -execdir 
rename -n "s/$(date +"%Y%m%d")/$(date -d "-1day" +"%Y%m%d")/" '{}' \;

P.s, since you are using csh shell, you need to use `...` instead of $(...), or better switch to new shells like bash, zsh.

find ./ -type f -name "*`date +"%Y%m%d"`*" -execdir 
rename -n "s/`date +"%Y%m%d"`/`date -d "-1day" +"%Y%m%d"`/" '{}' \;
αғsнιη
  • 41,407