bash - Find, Replace, Remove - with in file -


i'm using code:

awk 'begin { s = \"{$cnew}\" } /word_match/ { $0 = s; n = 1 } 1; end { if(!n) print s }' filename > new_filename 

to find match on word_match , replace line $cnew in file called filename results written new_filename

this works well. have issue may want delete line instead of replace it.

so set $cnew = '' works in blank line in file, not removing line.

is there anyway adapt awk command allow removal of line ?

the total aim :

  1. if there isn't line in file containing word_match add one, based on $cnew

  2. if there line in file containing word_match update line new value $cnew

  3. if $cnew ='' delete line contain word_match.

there 1 line in file containing word_match

thanks

awk -v s="$cnew" '/word_match/ { n=1; if (s) $0=s; else next; } 1; end { if(s && !n) print s }' file 

how works

  • -v s="$cnew"

    this creates s awk variable value $cnew. note use of -v neatly eliminates quoting problems can occur trying define s in begin block.

  • /word_match/ { n=1; if (s) $0=s; else next; }

    if current line matches word_match, set n 1. if s non-empty, set current line s. if not, skip rest of commands , start on over next line.

  • 1

    this cryptic shorthand print line.

  • end { if(s && !n) print s }

    at end of file, if n still not 1 , s non-empty, print s.


Comments