fedora
June 20, 2008, 3:11pm
1
should be a pretty simple problem, but it appears that I can't not specify the last column using sed
say I want to replace every aa with YY except the last colum in file test
$ cat /tmp/test
aa aa aa aa aa
c b c d aa a
e f ff mm aaa aaa 123
I was thinking about using
sed '/ [^ ]*$/!s/aa/YY/g' /tmp/test
but I just realized that this is totally wrong, so how can I specify the last column in sed?
Thanks!
I know this is not sed, but with awk I think is a lot simpler:
awk '{ for (i=1;i<NF;i++) if ($i=="aa") $i="YY"; print }' input_file.txt
fedora
June 20, 2008, 3:44pm
3
thanks for the answer, but can I just do it using sed?
With GNU sed you may try something like this:
sed "s/\baa\b/YY/g; s/YY$/aa/" input_file.txt
No better ideas... For now
fedora
June 20, 2008, 4:03pm
5
the thing is the last column of the file test is special, it may have something like "aaMM", which will be YYMM after the replacement, or "aaYY", which will be YYYY after the replacement, we can not just replace YY$ back to aa here.
robotronic:
With GNU sed you may try something like this:
sed "s/\baa\b/YY/g; s/YY$/aa/" input_file.txt
No better ideas... For now
This is very specific to the sample text provided and assumes that word boundary support, i.e. \b or \<, is not available in your version of sed.
$ sed -e 's/ aa$/ ++/' -e 's/aaa/+++/g' -e 's/aa/YY/g' -e 's/++/aa/' -e 's/+++/aaa/g' file
YY YY YY YY aa
c b c d YY a
e f ff mm aaa aaa 123
$
ripat
June 21, 2008, 5:30am
7
sed -r 's/\baa /YY /g' file
Seems to produce the desired output.