tags:

views:

287

answers:

2

I got a variable in a bash script that I need to replace. The only constant in the line is that it will be ending in "(x)xxxp.mov". Where x's are numbers and can be of either 3 or 4 of length. For example, I know how to replace the value but only if it is a constant:

echo 'whiteout-tlr1_1080p.mov' | sed 's/_[0-9]*[0-9][0-9][0-9]p.mov/_h1080p.mov/g'

How can I carry over the regex match to replacement line?

Edit:

Ok I just learned that grep can print only the match would it better to to do something like this?

urltrail=$(echo $@ | grep -o [0-9]*[0-9][0-9][0-9]p.mov)
newurl=$(sed 's/$urltrail/h$urltrail/g')

Hmm, tried the above but am getting a hang.

A: 

You're not piping the old path into sed, so sed is hanging waiting for input.

newurl=$(echo $@ |sed 's/$urltrail/h$urltrail/g')
scragar
Ack, I missed that, good catch scragar.
This will search for the literal text 'urltrail' anchored after the end of the line. You could use double quotes and do sed "s/$urltrail...", but that opens a whole different can of worms (eg, if $urltrail contains spaces or '/' or other regex meta-charactes.)
William Pursell
+1  A: 

Back Reference

sed 's/_\([0-9]*[0-9][0-9][0-9]\)p.mov/_h\1p.mov/g'

The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression.

Ian Yang
Well put Ian. Good to learn about sed and regex's and what they can do. Thanks for the help.