Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk - concatenate two string variable and assign to a third

Tags:

awk

gawk

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

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

like image 464
user3738926 Avatar asked Nov 19 '14 23:11

user3738926


People also ask

How do I concatenate strings in awk?

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 …

How do you concatenate 2 strings?

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.

How do you append text in awk?

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.

Which append operator used in awk is?

AWK - String Concatenation Operator.


2 Answers

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

like image 139
fedorqui 'SO stop harming' Avatar answered Oct 19 '22 05:10

fedorqui 'SO stop harming'


Could use sprintf to accomplish this:

awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file 
like image 42
Hongbo Liu Avatar answered Oct 19 '22 05:10

Hongbo Liu