Low Orbit Flux Logo 2 F

AWK How To Add Column In File

We are going to show you how to add a column to a file using AWK. It’s easy.

Here is an easy example. Let’s say that have a file called data.txt and you want to add a 5th column to it. The fifth column will be the sum of the first and third columns.

data.txt
1 2 3 4 4 3 2 1 5 6 7 8 8 7 6 5 1 5 6 2

To do this we start out by printing $0 which will include the entire existing line. We then sepecify the new column that we need to add as $1+$3. This will place the new column at the end.


awk '{print $0, $1+$3}' data.txt 

The output would look like this with an added column at the end.


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

You can write the output to a new file like this:


awk '{print $0, $1+$3}' data.txt  >> new_file.txt

We can add a column in the middle too. To do this we will need to specify each field individually placing our new column in the middle like this:


awk '{print $1, $2, $1+$3, $3, $4}' data.txt

The output would look like this:


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

You could also add an arbitrary string in the colum like this:


awk '{print $1, $2, "--", $3, $4}' data.txt 

The output would look like this:


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

Here is another example:


awk '{print $1, "abc", $2, $3, $4}' data.txt 

And the output:


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

Add two columns like this:


awk '{print $1, "abc", $2, $3, "xyz", $4}' data 

Output:


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