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

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

share|improve this question

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

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

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'
share|improve this answer

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' 
share|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

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

share|improve this answer

You must log in to answer this question.

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