Monday, February 25, 2008

HowTo: Do Awk with Loop

From recent posts, we have tried to remove the first word by statically specifying the matching string fields using awk and cut.

What if we need to remove the first word but retain the 2nd word up to Nth word of a line from a text file?

Here's a real quick and easy of dynamically looping awk to achieve the above effects.
Now let us try removing the first word while retaining the 2nd word up to the Nth word of a line from any text files.

# cat testfile.txt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Now we have removed the first word while retaining the rest from 2nd to Nth word of a line
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# cat testfile.txt | awk '{for(i=2;i<=NF;i++) printf ("%s ", $i);}'
output
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
we have removed the first word while retaining the rest from 2nd to Nth word of a line
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

That is all folks.

0 comments:

Sign up for PayPal and start accepting credit card payments instantly.
ILoveTux - howtos and news | About | Contact | TOS | Policy