Thursday, May 15, 2008

awk substr function

substr(string, start, length)
This returns a length-character-long substring of string, starting at character number start. The first character of a string is character number one. For example, substr("washington", 5, 3) returns "ing". If length is not present, this function returns the whole suffix of string that begins at character number start. For example, substr("washington", 5) returns "ington". This is also the case if length is greater than the number of characters remaining in the string, counting from character number start.

The descriptions about the "AWK Built-in Functions for String Manipulation" can be found here:

The following example will clear your understanding about the same function.

$ cat file.txt
FAN01MMAS2not set ahxpx0c1
FAN04MMAS4not set ptyx0c2
FAN02MMAS5not set 01cx67u
FAN06MMAS6not set opertxh2
FAN07MMAS2not set 9mcxh
FAN03MMAS8not set ptyx0c2

Required Output:
FAN01 (not set) MMAS2 ahxpx0c1
FAN04 (not set) MMAS4 ptyx0c2
FAN02 (not set) MMAS5 01cx67u
FAN06 (not set) MMAS6 opertxh2
FAN07 (not set) MMAS2 9mcxh
FAN03 (not set) MMAS8 ptyx0c2

$ awk '{

printf ("%s (%s) %s %s\n", one, three, two, rest)
}' file.txt

No comments:

© Jadu Saikia