I have 2 files with the following names:

File 1: RvA_X-IRB-bil-CA101-0+010000-20150327212332-055582-P

File 2: RvA_X-IRB-bil-CA101-1+020000-20150327212332-055582-P

I am using this command to match and then replace certain parts of the file names.

printf "%s\n" RvA_X-IRB-bil*P | sed -e 's/\(RvA_X-IRB\)-\bil-\(CA.*\)-\0+010000-\([0-9]\{8\}\).*-\([0-9]\{6\}\).*$/mv & \1-\2-\3-\4/'

The above mentioned command works fine for the file 1 but when I modify the command to work for the file 2, It doesn't work. The command for the second filename is given below:

printf "%s\n" RvA_X-IRB-bil*P | sed -e 's/\(RvA_X-IRB\)-\bil-\(CA.*\)-\1+020000-\([0-9]\{8\}\).*-\([0-9]\{6\}\).*$/mv & \1-\2-\3-\4/'

The only thing I have changed is this part \0+010000-\

  • \1 is a back reference for pattern in first parenthesis. Why you use \0,\1 form instead just 0 or 1? – Costas Mar 31 '15 at 13:35
  • 1
  • You can just remove unwanted parts sed 's/-bil\|-[01]+0[12]0000\|-[^-]*$//g' – Costas Mar 31 '15 at 13:49
  • 2
    Please edit your question and show us what your final output is supposed to be. You seem to want to rename your files, what are the new names you want to have? – terdon Mar 31 '15 at 13:57

With your regular expression you are recognizing:


in part because you are using \1 as others have pointed out. Note the repeated "RvA_X-IRB".

However, it could be important to note that you are using "\b" as well, and this is going to work only when you do have a "non-word" character in one side and a "word" character in the other. https://www.gnu.org/software/sed/manual/sed.html#Invoking-sed

I am not sure if this is intentional, and that is why I ommited the "b" in "-bil". In fact, I am quite surprised that your RE is working in the first case. For example:

echo "-bil" | sed 's#-\bil#GETIT#'

echo "-il" | sed 's#-\bil#GETIT#'


printf "%s\n" RvA_X-IRB-bil | sed 's/\(RvA_X-IRB\)-\bil/GETIT/'

printf "%s\n" RvA_X-IRB-il | sed 's/\(RvA_X-IRB\)-\bil/GETIT/'
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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