Home > database >  Changing the line after a match on Linux
Changing the line after a match on Linux

Time:01-27

I have a text file test.txt that has entries in it such as the following:

a line of text
another line
asdf
vkqaoc
coeiam
cieksm
pqocqoci
xmckdow
cqpszls
etc
etc etc etc

I need to search for a line and change the line that comes after it. I have come up with the following using awk that returns the line I want to change but I'm not that good with awk and I need a way to modify that line:

awk '/cieksm/{getline; print}' ./test.txt
pqocqoci

How can I modify that line using awk to say pqocqoci-changed or is there a better way? Assistance greatly appreciated and thank you!

CodePudding user response:

It's often easier to structure this sort of thing with a flag:

awk 'f{$0 = $0 "-changed"} 1{print} { f=/cieksm/}' test.txt

or (using the default rule)

awk 'f{$0 = $0 "-changed"} 1; { f=/cieksm/}' test.txt

CodePudding user response:

It's not clear (to me) the expected output

  1. just print pqocqoci-changed to stdout?
  2. print the whole file to stdout but change pqocqoci to pqocqoci-changed?
  3. update the source file by changing pqocqoci to pqocqoci-changed?

1: small modification to OP's current awk code:

$ awk '/cieksm/{getline var; print var "-changed"}' ./test.txt
pqocqoci-changed

2: adding code to dump all lines to stdout

$ awk '{print}/cieksm/{getline var; print var "-changed"}' ./test.txt
pqocqoci-changed

a line of text
another line
asdf
vkqaoc
coeiam
cieksm
pqocqoci-changed
xmckdow
cqpszls
etc
etc etc etc

3: using GNU awk to update the source file:

$ awk -i inplace '{print}/cieksm/{getline var; print var "-changed"}' ./test.txt
$ cat ./test.txt
a line of text
another line
asdf
vkqaoc
coeiam
cieksm
pqocqoci-changed
xmckdow
cqpszls
etc
etc etc etc

CodePudding user response:

Using GNU sed

$ sed '/cieksm/{n;s/.*/&-changed/}' input_file
a line of text
another line
asdf
vkqaoc
coeiam
cieksm
pqocqoci-changed
xmckdow
cqpszls
etc
etc etc etc
  •  Tags:  
  • Related