In awk, I have 2 fields: $1 and $2.
They are both strings that I want to concatenate and assign to a variable.
It does not have a specific operator to represent it. Instead, concatenation is performed by writing expressions next to one another, with no operator. For example: $ awk '{ print "Field number one: " $1 }' mail-list -| Field number one: Amelia -| Field number one: Anthony …
You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
You can use this sed -e '1 s/$/400/' -e '2 s/$/401/' -e '3 s/$/402/' -e '4 s/$/403/' file. txt to add at end of each line a specified character (e.g., here I used numbers 400-403). The number 1,2, and 3 reflects the line index.
AWK - String Concatenation Operator.
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 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
Could use sprintf
to accomplish this:
awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With