3

I have the following code where I am trying to replace assign with always @(*) using SED.

Essentially I am trying to ignore the ' in character class but SED still seems to match it. I don't want sed to catch the line if the line contains a ' (My regex is much more complicated than this but I want sed to catch lines which my regex and ignore the lines which match my regex but contain a ')

echo "assign sample_signal = '0;" | sed '/[^\x27]/ {s/assign/always @(*)/g}'

Result: always @(*) sample_signal = '0;

SLePort
  • 15,211
  • 3
  • 34
  • 44

3 Answers3

2

Try this please (GNU sed):

$ echo "assign sample_signal = '0;" | sed -n '/[\x27]/!{s/assign/always @(*)/g; p}'

$ echo "assign sample_signal = 0;" | sed -n '/[\x27]/!{s/assign/always @(*)/g; p}'
always @(*) sample_signal = 0;

Two mistakes you've made:
1. /[^\x27]/ means to match any character that is not a ', but there're many characters that are not ', so the regex will match anyway.
2. You didn't use -n which is to suppress the output, so match or not, substitude or not, the line will be printed out anyway.

So I changed to /[\x27]/!{} which means when \x27 matched, not execute the block {}.
(In sed's word, it will be executed when not matched.)
And by -n switch, and p in the block, lines with ' are ignored.

Til
  • 5,150
  • 13
  • 26
  • 34
2

Just use '\'' anywhere you need a ':

$ echo "f'oo" | sed 's/'\''o/X/'
fXo

$ echo "f'oo" | sed 's/[^'\'']o/X/'
f'X
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
1

You can enclose your sed command in double quotes and simply use /'/! to apply your command to lines not containing quotes:

echo "assign sample_signal = '0;" | sed "/'/! {s/assign/always @(*)/g;}"

If there is just one s command to apply, you can also omit the braces:

echo "assign sample_signal = '0;" | sed "/'/! s/assign/always @(*)/g"

As @EdMorton points out in comments, enclosing the command in double quotes may have unwanted effects. You may need to escape dollar sign(\$) to avoid unwanted variable expansion in your pattern) and double escape backslashes: \\\.

SLePort
  • 15,211
  • 3
  • 34
  • 44