Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .