'Changing the line after a match on Linux
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!
Solution 1:[1]
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
Solution 2:[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
Solution 3:[3]
It's not clear (to me) the expected output
- just print
pqocqoci-changedto stdout? - print the whole file to stdout but change
pqocqocitopqocqoci-changed? - update the source file by changing
pqocqocitopqocqoci-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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | markp-fuso |
