awk – split string using a delimiter

 

Using awk we can split a string with delimiter/string.

Examples:

Character as delimiter:

Using “:” as a delimiter for below example

$ echo "abc:def" | awk -F':' '{print $1}'

Output:

abc

$ echo "abc:def" | awk -F':' '{print "field1: "$1 "\nfield2: "$2}' 

Output:

field1: abc
field2: def

String as delimiter:

Using “bc” as delimiter for below example

$echo "abc:def" | awk -F'bc' '{print "field1: "$1 "\nfield2: "$2}' 

Output:

field1: a
field2: :def

To print number of fields:

To print number of fields use NF variable.

$ echo "abc:def" | awk -F'bc' '{print NF}'

Output: 

2

-Sany

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s