-1

I want to use sed (or any method) where I replace a string in a file.
The string is of the format "prv=x" where x is some integer. Is there a way in sed that I can designate this entire string to be replaced without specifying x?

1

Yes; to replace only the first occurence of the string in each line:

sed -i 's/prv=[0-9][0-9]*/replacement_string/' inputfile

Or:

sed -i 's/prv=[0-9]\{1,\}*/replacement_string/' inputfile 

To replace multiple occurences of the string in each line:

sed -i 's/prv=[0-9][0-9]*/replacement_string/g' inputfile

Or:

sed -i 's/prv=[0-9]\{1,\}*/replacement_string/g' inputfile

Using ERE syntax (if supported by your sed version), to replace only the first occurence of the string in each line:

sed -Ei 's/prv=[0-9]+/replacement_string/' inputfile

Or:

sed -Ei 's/prv=[0-9]{1,}/replacement_string/' inputfile

To replace multiple occurences of the string in each line:

sed -Ei 's/prv=[0-9]+/replacement_string/g' inputfile

Or:

sed -Ei 's/prv=[0-9]{1,}/replacement_string/g' inputfile
  • 2
    USing BRE you can also do sed 's/prv=[0-9]\{1,\}/replacement_string/' – 123 Jun 23 '15 at 15:14
  • 1
    Note that in there. It's the -i that is GNU specific and the least portable. -E is supported by GNU and many BSDs and is scheduled for inclusion in the next version of the POSIX standard. (the -r variant is GNU-specific and unintuitive/inconsistent so should be avoided IMO). – Stéphane Chazelas Jun 23 '15 at 15:19

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.