Given the following data:
aaa bbb aaa ccc aaa ddd
123 222 aaa aaa bbb ccc
If the value in column 4 is "ccc", I want to replace the value in column 6 on the same line with the word "end" using sed or awk.
Any ideas will be greatly appreciated.
Given the following data:
aaa bbb aaa ccc aaa ddd
123 222 aaa aaa bbb ccc
If the value in column 4 is "ccc", I want to replace the value in column 6 on the same line with the word "end" using sed or awk.
Any ideas will be greatly appreciated.
With awk
:
awk '$4=="ccc"{ $6="end" }1' file
The 1
at the end just prints the current line and is a shortcut for { print }
(see what is the meaning of 1 at the end of awk script).
I don't recommend using sed to perform operations on tabular data, but I offer a GNU sed solution anyway, given the question's tag.
sed -r 's:^(([^ ]* ){3}ccc [^ ]* )[^ ]*(.*)$:\1end\3:' file
I assumed there could be more than 6 columns. If not, then group \3 (.*)
isn't needed.
As you see the code isn't that readable and error-prone when written/modified, therefore an awk solution for example is preferable.
#!/usr/bin/python
k=open('filename','r')
for i in k:
o=i.strip().split(' ')
if ( o[3] == "ccc" ):
o[5]="end"
print " ".join(o)
output
aaa bbb aaa ccc aaa end
123 222 aaa aaa bbb ccc