0

I have a lot of files which have a certain pattern:

some123_name4.with5.number01-02_and6-other7.stuff.txt some123_name4.with5.number05-06_and6-other7.stuff.txt some123_name4.with5.number11-12_and6-other7.stuff.txt 

and I would like to rename them keeping the part in the middle number??-??. For example like:

different45_start.keep76.number01-02_but.change34_rest.txt different45_start.keep76.number05-06_but.change34_rest.txt different45_start.keep76.number11-12_but.change34_rest.txt 

I have played around with expr, %% and ? but I didn't even manage to extract the number??-?? part of the filename.

3 Answers 3

2

This ought to do it (replace with actual patterns)

#!/bin/bash for f in some123* ; do mv $f `echo $f | sed -e 's/some123_name4.with5/different45_start.keep76/' -e 's/and6-other7.stuff/but.change34_rest/'` done 
Sign up to request clarification or add additional context in comments.

2 Comments

Note that the above assumes the old file names all start and end with identical patterns
This very nice, simple and easy.
1

May I suggest you use regexp'es to extract your numbers from the old name into the new name? Then it's just a question about

  • creating a new subdirectory (just in case you make a mistake)
  • using "ls" to list the file names (with options for 1 (one) name per line, not following down into subdirs)
  • iterating over the file names

In each iteration,

  • set the new name
  • run the copy commande "cp" using the old and the new names (but as a trick, copy down into your new subdirectory)

All in all, something like this:

mkdir NEW ls -1d some* \ | while read FILE; do NEWFILE=`echo "$FILE" \ | sed 's|^some12\\([0-9]\\)_name\\([0-9]\\)[.]with\\([0-9]\\)[.]number\\([0-9][0-9]-[0-9][0-9]\\)_and\\([0-9]\\)-other\\([0-9]\\)[.]stuff[.]txt$|different\\2\\3_start.keep\\6\\5.number\\4_but.change\\1\\2_rest.txt|'` cp "$FILE" NEW/"$NEWFILE" done 

As you can see, due to the backticks (`) you have to use extra backslashes in the regexp.

Does this help you, as a start?

1 Comment

That looks very interesting! Thanks for showing something new and explain it :)
1

a possible solution using expr looks like the following:

for f in *number??-??*; do fixedPart=$(expr "$f" : '.*\(number[0-9][0-9]-[0-9][0-9]\).*') newName="different45_start.keep76.${fixedPart}_but.change34_rest.txt" mv "$f" "$newName" done 

1 Comment

This is the way I was actually searching for, thanks a lot for that!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.