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

link|improve this question

73% accept rate
feedback

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/'`"
link|improve this answer
feedback

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

file=ABC123
text=blah
new_file="${file:0:3}.$text.${file:3}"
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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