awk - concatenate two string variable and assign to a third


In awk, I have 2 fields: $1 and $2.

They are both strings that I want to concatenate and assign to a variable.

This question is tagged with awk gawk

~ Asked on 2014-11-19 23:20:29

The Best Answer is


Just use var = var1 var2 and it will automatically concatenate the vars var1 and var2:

awk '{new_var=$1$2; print new_var}' file

You can put an space in between with:

awk '{new_var=$1" "$2; print new_var}' file

Which in fact is the same as using FS, because it defaults to the space:

awk '{new_var=$1 FS $2; print new_var}' file


$ cat file
hello how are you
i am fine
$ awk '{new_var=$1$2; print new_var}' file
$ awk '{new_var=$1 FS $2; print new_var}' file
hello how
i am

You can play around with it in ideone:

~ Answered on 2014-11-19 23:22:16


Could use sprintf to accomplish this:

awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file

~ Answered on 2018-06-19 10:22:13

Most Viewed Questions: