How can I move the previous year to the end of the file name?

I have a list of files (thousands of them):

/path/2010 - filename.txt /path/2011 - another file name.txt 

Always following this pattern: #### - string.txt

I need to change them so that they look like this:

 /path/filename (2010).txt /path/another file name (2011).txt 

How can I do this quickly with bash, shell, terminal, etc.?

+3
unix bash regex shell rename
source share
4 answers

Unverified.

 find /path -name '???? - *.txt' -print0 | while read -d ''; do [[ $REPLY =~ (.*)/(....)\ -\ (.*)\.txt$ ]] || continue path=${BASH_REMATCH[1]} year=${BASH_REMATCH[2]} str=${BASH_REMATCH[3]} echo mv "$REPLY" "$path/$str ($year).txt" done 

Remove echo after the generated mv commands look correct.

+3
source share

Try the rename command:

 rename -n 's/(.*) - (.*)(\.txt)/$2 ($1)$3/' *.txt 

-n (- no-act) to preview.
Remove -n to perform the substitution.

+5
source share

I would prefer to add this as a comment, but I'm not yet allowed.

I asked a similar question and got some useful answers here:

https://unix.stackexchange.com/questions/37355/recursively-rename-subdirectories-that-match-a-regex

Perhaps one of these solutions can be tailored to your needs.

+1
source share

I know that you did not mark it with zsh , but you said shell . In any case, how to do this with the zmv function in zsh :

 autoload zmv # It not loaded by default zmv -nvw '* - *.*' '$2 ($1).$3' 

Remove -n when you are happy with the result.

-v does zmv verbose. -w implicitly creates a group for each pattern.

+1
source share

All Articles