Using Awk to Print Select Output

(1 vote, average 5.00 out of 5)

Awk is a very powerful utility, but its syntax is less than intuitive to a beginner. Here are a few common but very powerful things you can do with awk:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# print line 2 of the file
awk 'NR == 2' myFile.txt
 
# print column 2 of the file
awk '{print $2}' myFile.txt
 
# add up column 2
awk '{s += $4} END {print s}'
 
# print all the lines with more than 80 columns
awk 'length($0) > 80' myFile.txt
 
# print the number of lines in the file
awk 'END { print NR }' myFile.txt
 
# count the number of lines where column 2 is greater than column 1
awk '$2 > $1 {print i + "1"; i++}' myFile.txt
Partner Links:
Last Updated on Sunday, 18 July 2010 12:38  
Related Articles

» Redirect STDOUT And Other File Descriptors To A File in Bash

It is possible to redirect the output of a single command in Bash to a file using the > convention. For example, to redirect the STDOUT output to a file, use: ls -l > myfile.txt  However sometimes it would be better to redirect all output from multiple commands to a single file. This can be used by modifying the file descriptor, 1. First, we save a backup of the file handle for STDOUT and then change it to point to the desired file. We can then later restore STDOUT from the...

» Combine MP4/M4V Files in Linux/Ubuntu

You may want to combine multiple mp4/m4v video files into one continuous video. In order to do this, you need to install the gpac library of programs onto Ubuntu. Open up Terminal and run:sudo apt-get install gpac This will install the gpac library. One of the programs included with it is MP4Box, which you can use to concatenate the video files. If you are using 64 bit Linux or get an error like MP4Box: error while loading shared libraries: libgpac.so: cannot open shared object file: No such...

» Block Comments in Perl

Like many scripting languages, there is no real way to do block comments in Perl.  The proper way to do a block comment is simply to comment out each line with a # along the left side, and in fact many popular text editors such as vim and emacs facilitiate this behavior (we have a tutorial on how to do it in emacs ).There is an easier way to make the compiler ignore a block of code if you are interested in a less visibly-obvious solution.  This is great for short-term solutions but it...