awk - concatenate two string variable and assign to a third

69

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


114

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

Test

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

You can play around with it in ideone: http://ideone.com/4u2Aip

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


17

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: