1

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!

markp-fuso
  • 28,790
  • 4
  • 16
  • 36
Kyle
  • 11
  • 3
  • [This](https://stackoverflow.com/questions/20464726/replace-line-after-match/20470583#20470583) might help you. – potong Jan 26 '22 at 17:17

3 Answers3

2

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
HatLess
  • 10,622
  • 5
  • 14
  • 32
2

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
William Pursell
  • 204,365
  • 48
  • 270
  • 300
1

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
markp-fuso
  • 28,790
  • 4
  • 16
  • 36