Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

gawk use to replace a line containing a pattern with multiple lines using variable

I am trying to replace a line containing the Pattern using gawk, with a set of lines. Let's say, file aa contains

aaaa
ccxyzcc
aaaa
ddxyzdd

I'm using gawk to replace all lines containing xyz with a set of lines 111\n222, my changed contents would contain:

aaaa
111
222
aaaa
111
222

But, if I use:

gawk -v nm2="111\n222" -v nm1="xyz" '{ if (/nm1/) print nm2;else print $0}' "aa"

The changed content shows:

aaaa
ccxyzcc
aaaa
ddxyzdd

I need the entire lines those contain xyz i.e. lines ccxyzcc and ddxyzdd having to be replaced with 111 followed by 222. Please help.

Upvotes: 2

Views: 245

Answers (4)

Sundeep
Sundeep

Reputation: 23667

The problem with your code was that /nm1/ tries to match nm1 as pattern not the value in nm1 variable

$ gawk -v nm2="111\n222" -v nm1="xyz" '$0 ~ nm1{print nm2; next} 1' aa
aaaa
111
222
aaaa
111
222

Thanks @fedorqui for suggestion, next can be avoided by simply overwriting content of input line matching the pattern with required text

gawk -v nm2="111\n222" -v nm1="xyz" '$0 ~ nm1{$0=nm2} 1' aa


Solution with GNU sed

$ nm1='xyz'
$ nm2='111\n222'
$ sed "/$nm1/c $nm2" aa
aaaa
111
222
aaaa
111
222

The c command would delete the line matching pattern and add the text given

Upvotes: 3

Ljm Dullaart
Ljm Dullaart

Reputation: 4969

Passing variables as patterns to awk is always a bit tricky.

awk  -v nm2='111\n222'  '{if ($1 ~ /xyz/){ print nm2 } else {print}}'

will give you the output, but the 'xyz' pattern is now fixed.

Passing nm1 as shell variable will also work:

nm1=xyz
awk  -v nm2='111\n222'  '{if ($1 ~ /'$nm1'/){ print nm2 } else {print}}' aa

Upvotes: 0

user3439894
user3439894

Reputation: 7555

This is how I'd do it:

$ cat aa
aaaa
ccxyzcc
aaaa
ddxyzdd
$ awk '{gsub(/.*xyz.*/, "111\n222")}1' aa
aaaa
111
222
aaaa
111
222
$ 

Upvotes: 1

Inian
Inian

Reputation: 85530

When using awk's ~ operator, and you don't need to provide a literal regex on the right-hand side.

Your command as-such with the correction of improper syntax would be something like,

gawk -v nm2="111\n222" -v nm1="xyz" '{ if ( $0 ~ nm1 ) print nm2;else print $0}' input-file

which produces the output.

aaaa
111
222
aaaa
111
222

Upvotes: 1

Related Questions