Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Basically, all I want to do is alter outputs if the input matches a filter, but the part being altered isn't what is being filtered (or I would use sed). The problem so far is that my awk is only outputting the altered lines.

Quick example, put this in test.txt:

orange beet pear cowmilk
apple pear berry cowmilk
orange melon cherry cowmilk

If I use the code:

awk /orange/'{gsub(/cow/,"cow~"); print}' test.txt

I get:

orange beet pear cow~milk
orange melon cherry cow~milk

When I would rather get:

orange beet pear cow~milk
apple pear berry cowmilk
orange melon cherry cow~milk

I see you can do || with awk, but I haven't been able to figure out how to make that fit with the gsub above.

For bonus appreciation, what I'd really like to do is add color instead of ~, but that totally breaks, i.e.

awk /orange/'{gsub(/cow/,"cow'\e[1;34m'"); print}' test.txt

gives me an error about \ not being the end of the line.

share|improve this question

2 Answers 2

up vote 8 down vote accepted

For colour, you need to specify the actual ESC character (not the escaped form \e).. the value is hex \x1B or octal \033. The following scripts colour the dash - and print all input lines

awk '/orange/{gsub(/cowmilk/,"cow\x1B[1;34m-\x1B[0mmilk")} {print}' "$file"

sed '/orange/{s/cowmilk/cow\x1B[1;34m-\x1B[0mmilk/g}' "$file"
share|improve this answer
    
Ah, great! Thanks. I didn't realize just sed could do this too. –  Ken Oh Jun 29 '12 at 16:20

For printing each line after modifying only a few, add a separate condition that always evaluates to true, like (1):

awk '/orange/{gsub("cow", "cow~")} 1' "$file"

You could also have {print} explicitly:

awk '/orange/{gsub("cow", "cow~")} {print}' "$file"

Remember that each awk statement consists of a condition and a statement clause:

condition {statements}

But each of these is optional, if you do not include {statements}, then {print} is used. If you do not include condition, then 1 is used.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.