Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I need to rename the following:

file_001_loremipsum.png
file_002_dolor.png
file_003_sit.png
file_004_amet.png
file_105_randomness.png

into

upl_loremipsum.png
upl_dolor.png
upl_sit.png
upl_amet.png
upl_randomness.png

How do I make it happen with just one simple line of terminal command?

share|improve this question

2 Answers 2

The Internet is a encyclopedia that unless you know the answer, you won't find it. So I took a little time to understand the EXTREMELY simple solution:

rename

the solution to the above example is:

rename -v -n 's/file_\d{1,3}/upl/' file_*.png

// rename [options] [regex search/replace] [in these files]
// -v = verbose, display what you are doing on screen
// -n = "do Not, just show what might happen", in other words, use '-n' if you want to test the end result

rename MAY take regex as the arguments.

What we are looking at is the content between the apostrophes '. You can place regex separated by /.

formula: s/(1)/(2)/ where:

(1) = search,

(2) replace.

So, familiarize youself with regex, and enjoy pattern based batch file renaming!

share|improve this answer

This can be done with little magic of bash parameter expansion!

for f in file_[0-9]*_*; do mv $f upl_${f#file_[0-9]*_}; done

file_[0-9]*_*; - First pattern is used to go trough all files that begin with 'file_anynumber_'
${f#file_[0-9]*_} - The second pattern file_[0-9]*_ is used in parameter expansion which tells bash to remove 'file_anynumber_' from the begging of the string.

For more information on Parameter expansion:

man bash
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.