1

I need to use sed to modify a document called "case" with the lines example="value" where value can take any 2 o 3 characters integer, for example:

example=55
example=777
otherthing=anothervalue

I want to use sed to modify both of the example lines into two lines called example=000

I have tried to use

sed -i -e "s/example=*/example=000/g" case 

to modify them both at the same time, but obviously it did not worked. What I need to know is how to make sed take any 2 or 3 characters after the =

Inian
  • 12,807
Unuser
  • 11
  • From your question it sounds like the problem is modifying 2 matching lines at the same time - did you have a script that modifies 1 line? – Ed Morton Aug 11 '21 at 20:49

1 Answers1

7

You're confusing the different meanings of * for Shell Filename Expansion and Posix Basic Regex (BRE).

In Regex, * is the quantifier for the character in front of it, so =* means 0 or more occurrences of =. If you want "any number of any character", use .*.

sed -i -e 's/example=.*/example=000/' case 

Some more hints:

  • You can leave out the g modifier, as your string likely appears only once per line.
  • If you don't want to also match another_example=value, use ^example=.* to make sure that example is at the start of the line.
  • Instead of . for any character, you can use [0-9] or [[:digit:]]] to match only numbers.
  • Instead of *, you can use + quantifier, that means 1 or more characters (must be escaped to \+ for BRE in GNU sed or written as \{1,\} for general sed).

To match only 2 or 3 characters, you can do

sed -i -e 's/example=.\{2,3\}/example=000/' case 

or using Extended Regex (ERE) (sed -E):

sed -i -E -e 's/example=.{2,3}/example=000/' case 
pLumo
  • 22,565
  • +1. The OP could use ^example=[0-9]\{1,\} or ^example=[[:digit:]]\{1,\} instead of . to limit the match to digits. Also, some versions of sed (e.g. GNU sed) understand \+ in BRE to mean one-or-more, same as + in ERE (this is not POSIX BRE, but neither is | or \| for alternation). e.g. ^example=[[:digit:]]\+. Personally, I mostly use sed -E for ERE except for the most trivial of regexes. – cas Aug 12 '21 at 06:55
  • Thanks, added that to my hints. – pLumo Aug 12 '21 at 07:06