In this tutorial we will learn, how to use awk command to print columns from file. This tip is often used by Unix/Linux System Administrator.
AWK Command
Awk is one of the awesome tool for processing the rows and columns.It also has feature to search keywords/strings . Awk command is widely used by Unix/Linux users for text processing the files. We can also use regex expression with awk command.
print columns from files with awk command
As per the post title, we will explain some tips on awk command to print columns from file.
For practical we will use the file called employee.list . I have created this file in /tmp and lets have a look on its content.
Print single columns from file
To print the single column from file,use below given syntax
awk '{print $column-number}' /path/file-name
Example: Printing column no. 2
awk '{print $2}' /tmp/employee.list
Example: In another example, we will print column no. 4
awk '{print $4}' /tmp/employee.list
Below is the screenshot of both awk command example. (compare the column no. shown in Figure 1)
Print multiple columns from file
Printing multiple columns require comma(,) separating each defined multiple column number in awk command.
Use below given syntax for printing multiple columns by using awk command.
awk '{print $column-number1,$column-number2,$column-number-N'} /path/file-name
Example 1: Now we will print column number 2,column number 3 and column number 5
awk '{print $2,$3,$5}' /tmp/employee.list
See the output in below given screenshot
Printing single or multiple columns by removing field-separator
I hope from above examples, you learned about using awk command to print single and multiple columns from file.
What if you have field-separator in files like semicolon( ; ),colon( : ),comma( , ),Tab,space etc. ?
In this case, we have option called –field-separator . Or in short we can also use -F .
Use the given below syntax for awk with field-separator option
awk -F'separator' '{print $column-number-N}' /path/file-name
Lets take an example of /etc/passwd file. We see colon(:) is field-separator there.
Task: Here our task is printing column no. 6 from /etc/passwd which has value of user’s home directory path .
Whereas we also have to deal with separator that is colon ( : ) .
See the result in below given screenshot (Because /etc/passwd file output was long, I have taken screenshot of upper portion only)
Similarly, We can print multiple columns with field-separator
Here, in this example we will print column no. 1 , column number 6 and column no. 7 from /etc/passwd.
awk -F':' '{print $1,$6,$7}' /etc/passwd
Check the result in your system 🙂 , it will help you to understand
Prints the entire file using awk command
This one is interesting command.Printing the entire file using awk command .
It is similar to cat file-name
Syntax:
awk '{print $0}' /path/filename
Example: We are showing this example in below given screenshot