Tuesday, August 3, 2010

Awk - powerful tool

Awk is a scripting language that can be used in shell. Please find here some examples:


  1. We've got a file that contains lines and columns (separated with spaces). We want to print only the contents of 3rd column.

    cat file.txt | awk '{print $3}'

  2. Print last column:

    cat file.txt | awk '{print $NF}'

    $NF means for awk the last argument (here: column)

  3. Print the first expression before '/' sign:

    cat file.txt | awk -F '/' '{print $1}'

    Using -F option you can set different separators for awk arguments.

  4. Another example. Printing last column + some text before it + some text after:

    cat file.txt | awk '{print "cp /home/"$1" "$1}'

    If you have filenames from /home directory in the file.txt this will prepare copying those file to current directory.

No comments:

Post a Comment