Low Orbit Flux Logo 2 D

AWK How To Concatenate String

We are going to show you how to concatenate strings with AWK. This is easy but might not always work the way you would expect.

Here is an example showing how you would concatenate an arbitrary string literal with the string variable for column 2.


awk '{print  "abc"$2}' data.txt 

Here is the output:


abc2
abc3
abc6
abc7
abc5

If you list two strings with a comma, they will be concatenated with the field separator placed between them.


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

Output:


abc 2
abc 3
abc 6
abc 7
abc 5

Here we concatenate a custom defined variable with an arbitrary string literal and the variable for column two. Nothing will separate these string variables. They will be displayed exactly like this.


awk 'BEGIN{x="test"}{print  x"abc"$2}' data.txt 

Output:


testabc2
testabc3
testabc6
testabc7
testabc5

Here we do almost the same thing wexcept that we explicitly add spaces.


awk 'BEGIN{x="test"}{print  x" abc "$2}' data.txt 

Output:


test abc 2
test abc 3
test abc 6
test abc 7
test abc 5

Here we print out two string variables. They are concatenated with the field separator automatically.


awk 'BEGIN{x="test";y="asdf";  print x,y}' data.txt 

Output:


test asdf

If we try adding two string variables together with a plus sign they will NOT be concatenated. They will be added together.


awk 'BEGIN{x="test";y="asdf";  print x+y}' data.txt 

The result is zero. Probably not what you would have wanted.


0

You can concatenate and print these string variables like this:


awk 'BEGIN{x="test";y="asdf";  print x" "y}' data.txt 

Output:


test asdf

You could do the same thing but concatenate them with an arbitrary string.


awk 'BEGIN{x="test";y="asdf";  print x" -- "y}' data.txt 

And this would be the output:


test -- asdf