awkgawk

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.


Solution

  • 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