Search code examples
regexbashsedregex-negationsingle-quotes

Negate Single Quote In Character Class


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;


Solution

  • 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.