Saturday, 21 November 2015

Common Functions in AWK

LENGTH: Return the length of the string

$ echo "AWK Tutorial" | awk '{print length($0)}';

Output: 12

INDEX : Returns the position of the required in string.
syntax : index(<string>,<string to be find>)

$ V_Text_String="You are learning AWK functions";
$ echo $V_Text_String | awk '{print index ($0,"AWK")}'

Output: 18


SUBSTR : returns a part of the string
syntax   : substr(<string>,<position>,<length>)

$ V_Text_String="You are learning AWK functions";
$ echo $V_Text_String | awk '{print substr($0,1)}'

Output: You are learning AWK functions
function has returned complete string starting from 1st position

$ echo $V_Text_String | awk '{print substr($0,2)}'

Output: ou are learning AWK functions
function has returned complete string starting from 2nd position

$ echo $V_Text_String | awk '{print substr($0,1,8)}'

Output: You are 
function has returned string starting from 1st position to 8th position

SPLIT : It is used to split the string
syntax: split(<string>,<array>,<delimiter>)

$ V_Text_String="Apple,Nokia,Samsung,MI";
$ echo $V_Text_String | awk '{print split($0,V_Prod,",")}'

Output: 4 ( basically returned number of field separated by  comma"," or We can say the length of the array V_Prod)

$ echo $V_Text_String | awk 'split($0,V_Prod,",") {print V_Count} END{for(k in V_Prod) print k, V_Prod[k] }'

Output:
1 Apple
2 Nokia
3 Samsung
4 MI

Note: split() function is used to create Associative Arrays.

TOLOWER : Convert string into lower case
syntax       : <tolower(<string>)

$ V_Text_String="Apple,Nokia,Samsung,MI";
$ echo $V_Text_String | awk '{print tolower($0)}'

Output: apple,nokia,samsung,mi

TOUPPER  : Convert string into upper case
syntax       : <tolower(<string>)

$ V_Text_String="Apple,Nokia,Samsung,MI";
$ echo $V_Text_String | awk '{print toupper($0)}'

Output: APPLE,NOKIA,SAMSUNG,MI

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...