I have read and search, but I don't understand what's wrong with it, I want to match: a space, the string 00011, and either a space or a new line.

sed 's:\(\s\)\(00011\)\([\s\n]\):\1$03\3:g'

EDIT: the data looks like this:

ADD    00000 00001 00011
LSH    00011 00100 01111
ADD    00011 10100 00010
JSR    00011101000111010101100010

and $03 is just a string to replace the 00011

I want to end up with something like this:

ADD    00000 00001 $03
LSH    $03 00100 01111
ADD    $03 10100 00010
JSR    00011101000111010101100010

Thanks

  • 1
    What does your input data look like? Note that since sed reads newline-delimited data, it will never see the newlines themselves. – Kusalananda Sep 26 at 9:04
  • What does that $03 stand for? It won't be expanded due to the single quotes, and if it were, it would expand to e.g. bash3 (given your shell is bash). – RudiC Sep 26 at 9:10
up vote 3 down vote accepted

sed works on a line at a time and it will strip the newlines when processing each line.

So, in order to do what you want, you should match the end of line anchor ($) rather than a literal newline character.

This should work:

sed 's:\(\s\)\(00011\)\(\s\|$\):\1$03\3:g'
  • 1
    I already tried that, but I missed the backslash before the pipe, thanks, it works perfectly. – onlycparra Sep 26 at 9:36
  • 1
    This would fail for data such as 00011 00011. – Kusalananda Sep 26 at 9:48
  • 1
    even with the g? – onlycparra Sep 26 at 10:26
  • 2
    @onlycparra That's correct, the /g doesn't help here, since the space between matches will be matched at the end of the first regex, so it will not be considered at the start of the second regex match. You can test that yourself. Matching word boundaries is definitely better here! – Filipe Brandenburger Sep 26 at 10:36
$ sed 's/\<00011\>/$03/g' file
ADD    00000 00001 $03
LSH    $03 00100 01111
ADD    $03 10100 00010
JSR    00011101000111010101100010

The \< and \> matches the zero-width word boundaries at the start and end of a word, respectively. BSD sed would also recognise [[:<:]] and [[:>:]], and GNU sed also understands \b as a word boundary.

sed will never see the newlines in the input data. Also, \s is specific to GNU sed. To match a space character in standard sed just use a literal space (to match a space-or-tab, use [[:blank:]]).

  • 1
    very complete and informative, thanks – onlycparra Sep 26 at 9:39

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.