How to use awk concatenate string in linux/unix

Awk concatenate string is a basic capability that supports connecting two or more strings.

synatx

➜  ~ awk 'BEGIN {s1="string1";s2="string2"; print s1 "delimiter" s2;}'


➜  ~ awk 'BEGIN {s1="string1 delimiter";s2="string2";s3=s1 s2; print s3;}'

# use awk variable: OFS
➜  ~ awk 'BEGIN {s1="string1"; s2="string2"; OFS="delimiter"; print s1,s2}'

examples

In the following example, we can use the concatenate string and output the merged string.

➜  ~ awk 'BEGIN {s1="concatenate"; s2="string"; print s1 "-" s2;}'
concatenate-string

➜  ~ awk 'BEGIN {s1="concatenate-"; s2="string"; s3=s1 s2; print s3;}'
concatenate-string

➜  ~ awk 'BEGIN {s1="concatenate"; s2="string"; OFS="-"; print s1,s2}'
concatenate-string

The above three methods can concatenate strings.

However, we recommend using a third-party method to concatenate strings using awk OFS variables.

The advantage of this method is that when we need to connect N (N>2) strings, not You need to use a delimiter after each string to connect them.

➜  ~ awk 'BEGIN {s1="a";s2="b";s3="c";s4="d";OFS="-";print s1,s2,s3,s4;}'
a-b-c-d

When we process the program log file, we need to separate the fields according to the delimiter, and then use the new delimiter to connect the string.

As the following example, to test the string :

"12323:192.168.23.1#chrome#/url/awk-concatenate-string:get"

we need to get the url and ip, and use “|” as the delimiter to connect the two strings.

➜  ~ echo "12323:192.168.23.1#chrome#/url/awk-concatenate-string:get" | awk 'BEGIN{FS="[:#]";OFS="|"} {print $2,$4}'
192.168.23.1|/url/awk-concatenate-string
➜  ~

Add a Comment

Your email address will not be published.