Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Just using shell scripting, how can I insert text into the middle of a file name. The file has a predictable pattern, let's say 3 letters and 3 numbers and I want to insert text in the middle of those 2 patterns. Say ABC123 is the file name. As a result, the file name should be ABC.blah.123

share|improve this question
add comment

2 Answers

You can use sed to change the file name string:

echo $filename | sed -r 's/^([a-zA-Z]{3})([0-9]{3})$/\1.blah.\2/'

That means: Take the first 3 characters of the string if they are letters, add the string `.blah.' and add the last 3 characters of the string if they are numbers.

If you e.g. want to rename the file you could do:

mv "$filename" "`echo $filename | sed -r 's/(^[a-zA-Z]{3})([0-9]{3})$/\1.blah.\2/'`"
share|improve this answer
add comment

Assuming you have a recent enough bash, you can use parameter substrings:

file=ABC123
text=blah
new_file="${file:0:3}.$text.${file:3}"
share|improve this answer
add comment

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.