hot to specify the last column in sed?

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

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 :slight_smile:

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.

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
$
sed -r 's/\baa /YY /g' file

Seems to produce the desired output.