Reputation: 307
I have many files and all of them have the word text
in them.
like test text22 test.mp3
"test" can include all kinds of characters -> -/()(&%0-9...
Now I want to rename every file so that a underscore is added before every "text" like test_test22 test.mp4
. Is there a straight forward way to do this?
Upvotes: 1
Views: 173
Reputation: 37404
I assume you don't want to add the underscore but replace leading space with it like in your example (but then again it had mp3 -> mp4 so just making sure):
$ ls
test text22 test.mp3
text22 test.mp3
$ for f in *text*; do "echo ${f/ text/_text}" ; done
test_text22 test.mp3
text22 test.mp3
To mv
replace the echo with mv "$f" "${f/ text/_text}"
Upvotes: 0
Reputation: 6995
Another way to do it which illustrates the (often very useful) use of regular expression matching in Bash.
#!/bin/bash
for file in *
do
if [[ $file =~ (.*)text(.*) ]] ; then
mv "$file" "${BASH_REMATCH[1]}text_${BASH_REMATCH[2]}"
fi
done
This would be especially useful if you want to do something other than just rename the files.
Upvotes: 0
Reputation: 88601
With Perl‘s standalone rename command:
rename -n 's/ (text[0-9]{1,2})/_$1/' *text*
If everything looks okay, remove option -n
.
Upvotes: 1