Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call the split function in awk to split a string on "\."?

Tags:

bash

awk

How do I use the split function to split by "\."?

For example, first consider splitting by ::

echo "03:26:12" | awk '{split($0,a,":"); print a[3] a[2] a[1]}'

Which produces this output:

122603

But if the incoming string is instead:

echo "03\.26\.12" | awk '{split($0,a,???); print a[3] a[2] a[1]}'

With desired output:

122603

What should the ??? be?

like image 954
user1268200 Avatar asked Mar 26 '12 15:03

user1268200


People also ask

Which function in awk is used to divide a string into pieces separated by the field seperator and store the pieces in an array?

The patsplit() function splits strings into pieces in a manner similar to the way input lines are split into fields using FPAT (see Defining Fields by Content).

How do I split a string in bash?

In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.

How does awk split columns?

Here is a simple awk command to split it into 3 columns. In the above awk command, we use -F option to specify input delimiter as comma, -OFS option to specify the output field delimiter, that is the delimiter to be used for output file. We issue a print statement within curly braces {} to print the columns 1, 2, 3.


2 Answers

echo "03\.26\.12" | awk '{split($0,a,"\\\."); print a[3] a[2] a[1]}'

This gives the same output.

like image 164
Umae Avatar answered Oct 15 '22 17:10

Umae


You must escape both characters:

echo "03\.26\.12" | awk '{split($0,a,/\\\./); print a[3] a[2] a[1]}'

Result:

122603
like image 39
Birei Avatar answered Oct 15 '22 15:10

Birei