Reputation: 21
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!
Upvotes: 2
Views: 145
Reputation: 11227
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
Upvotes: 2
Reputation: 212248
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
Upvotes: 3
Reputation: 34484
It's not clear (to me) the expected output
pqocqoci-changed
to stdout?pqocqoci
to
pqocqoci-changed
?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
Upvotes: 1