1

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?

0

3 Answers 3

1

With Perl‘s standalone rename command:

rename -n 's/ (text[0-9]{1,2})/_$1/' *text*

If everything looks okay, remove option -n.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.