Question

I have a text file with a series of numbers:

1 2 4 2 2 6 3 4 7 4 4 8 2 4 6 5 5 8

I need to have every third field multiplied by 3, so output would be:

1 2 12 2 2 18 3 4 21 4 4 24 2 4 18 5 5 24

Now, I've hammered out a solution already, but I know there's a quicker, more elegant one out there. Here's what I've gotten to work:

xargs -n1 < input.txt | awk '{printf NR%3 ? "%d " : $0*3" ", $1}' > output.txt

I feel that there must be an awk one-liner that can do this?? How can I make awk look at each field (instead of each record), thus not needing the call to xargs to put every field on a different line? Or maybe sed can do it?

Was it helpful?

Solution

Try:

awk '{for (i=3;i<=NF;i+=3)$i*=3; print}' input.txt > output.txt

I have not tested this yet (posted on my iPod). The print command without parameters should print out the whole (partially modified) line. You might have to set OFS=" " in the BEGIN section to get the blank as the separator in the output.

OTHER TIPS

this line would work too:

awk -v RS="\\n| " -v ORS=" " '!(NR%3){$0*=3}7' file
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top