Guys, I need to search and replace an alphanumeric string using SED.

Search String: Test:rXXXXX, where XXXXX will always be a 5 digit number

Replace String: Test:rYYYYY, where YYYYY will always be a 5 digit number

I have come up with the following :

echo 'Test:r12345' | sed 's/Test:r[0-9][0-9][0-9][0-9][0-9]$/Test:rYYYYY/g'

This works currently.

Is there a better way to achieve this? I don't want to use '[0-9]' 5 times in the expression

link|improve this question

71% accept rate
feedback

migrated from stackoverflow.com Apr 23 '11 at 22:04

This question came from our site for professional and enthusiast programmers.

3 Answers

up vote 1 down vote accepted

Just another one with sed with a small modification to match the "Test:r" subexpression making the replacement a bit more terse

echo 'Test:r12345' | sed 's/\(Test:r\)[0-9]\{5\}/\1YYYYY/g'
link|improve this answer
feedback

Use this syntax instead:

[0-9]{5}

This requires you to pass '-r' to sed, so the new example will be:

echo 'Test:r12345' | sed -r 's/Test:r[0-9]{5}$/Test:rYYYYY/g' 
link|improve this answer
2  
It would be better to point that sed/awk/grep use POSIX regular expressions and why the additional -r is required. en.wikipedia.org/wiki/Regular_expression#Syntax – mhitza Apr 23 '11 at 21:11
2  
Also, the -r is not strictly necessary, but it changes the syntax somewhat if it is omitted: sed 's/Test:r[0-9]\{5\}/...' – William Pursell Apr 23 '11 at 23:50
Thanks guys, Any idea why sed -i 's/Test:r[0-9]\{5\}$/Test:rYYYYY/g' myfile.txt wouldnt work? Is the syntax wrong – smokinguns Apr 25 '11 at 4:31
feedback

well, based on your sample, you can just replace the 2nd field using awk

echo 'Test:r12345' | awk -F":" '{$2="rYYYYY"}1' OFS=":"

There is no need to create complex regular expression. KISS

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.