Common string processing functions of Awk

Source: Internet
Author: User
Tags string find uppercase character

Gsub (regexp, replacement [, target])

Search target for all of the longest, leftmost, nonoverlapping matching substrings it can find and replace them with replacement. the 'G' in gsub () stands for "global," which means replace everywhere. for example:

{Gsub (/Britain/, "United Kingdom"); print}

Replaces all occurrences of the string 'Britain 'with 'United Kingdom' for all input records.

The gsub () function returns the number of substitutions made. if the variable to search and alter (target) is omitted, then the entire input record ($0) is used. as in sub (), the characters '&' and '\' are special, and the third argument must be assignable.

Index (in, find)

Search the string in for the first occurrence of the string find, and return the position in characters where that occurrence begins in the string in. Consider the following example:

$ Awk 'in in {print index ("peanut", "")}'

If find is not found, index () returns zero. (Remember that string indices in awk start at one .)

Length ([string])

Return the number of characters in string. if string is a number, the length of the digit string representing that number is returned. for example, length ("abcde") is five. by contrast, length (15*35) works out to three. in this example, 15*35 = 525, and 525 is then converted to the string "525", which has three characters.

If no argument is supplied, length () returns the length of $0.

NOTE: In older versions of awk, the length () function cocould be called without any parentheses. doing so is considered poor practice, although the 2008 POSIX standard explicitly allows it, to support historical practice. for programs to be maximally portable, always supply the parentheses.

If length () is called with a variable that has not been used, gawk forces the variable to be a scalar. other implementations of awk leave the variable without a type. (d.c .) consider:

$ Gawk 'in in {print length (x); x [1] = 1 }'

Error --> gawk: fatal: attempt to use scalar 'X' as array

$ Nawk 'in in {print length (x); x [1] = 1 }'

If -- lint has been specified on the command line, gawk issues a warning about this.

With gawk and several other awk implementations, when given an array argument, the length () function returns the number of elements in the array. (c. e .) this is less useful than it might seem at first, as the array is not guaranteed to be indexed from one to the number of elements in it. if -- lint is provided on the command line (see Options), gawk warns that passing an array argument is not portable. if -- posix is supplied, using an array argument is a fatal error.

Match (string, regexp)

Search string for the longest, leftmost substring matched by the regular expression, regexp and return the character position, or index, at which that substring begins (one, if it starts at the beginning of string ). if no match is found, return zero.

The regexp argument may be either a regexp constant (/... /) or a string constant ("... "). in the latter case, the string is treated as a regexp to be matched.

The order of the first two arguments is backwards from most other string functions that work with regular expressions, such as sub () and gsub (). it might help to remember that for match (), the order is the same as for '~ 'Operator: 'string ~ Regexp '.

The match () function sets the built-in variable RSTART to the index. it also sets the built-in variable RLENGTH to the length in characters of the matched substring. if no match is found, RSTART is set to zero, and RLENGTH to 0.

For example:

If ($1 = "FIND ")

Regex = $2

Else {

Where = match ($0, regex)

If (where! = 0)

Print "Match of", regex, "found ",

Where, "in", $0

This program looks for lines that match the regular expression stored in the variable regex. this regular expression can be changed. if the first word on a line is 'Find ', regex is changed to be the second word on that line. therefore, if given:

FIND ru + n

My program runs

But not very quickly

FIND Melvin

JF + KM

This line is property of Reality Engineering Co.

Melvin was here.

Awk prints:

Match of ru + n found at 12 in My program runs

Match of Melvin found at 1 in Melvin was here.

If array is present, it is cleared, and then the zeroth element of array is set to the entire portion of string matched by regexp. if regexp contains parentheses, the integer-indexed elements of array are set to contain the portion of string matching the corresponding parenthesized subexpression. for example:

$ Echo foooobazbarrrrr |

> Gawk '{match ($0,/(fo +). + (bar *)/, arr)

> Print arr [1], arr [2]}'

-| Foooo barrrrr

In addition, multidimensional subscripts are available providing the start index and length of each matched subexpression:

$ Echo foooobazbarrrrr |

> Gawk '{match ($0,/(fo +). + (bar *)/, arr)

> Print arr [1], arr [2]

> Print arr [1, "start"], arr [1, "length"]

> Print arr [2, "start"], arr [2, "length"]

> }'

-| Foooo barrrrr

There may not be subscripts for the start and index for every parenthesized subexpression, since they may not all have matched text; thus they shoshould be tested for with the in operator (see Reference to Elements ).

Split (string, array [, fieldsep [, seps])

Divide string into pieces separated by fieldsep and store the pieces in array and the separator strings in the seps array. the first piece is stored in array [1], the second piece in array [2], and so forth. the string value of the third argument, fieldsep, is a regexp describing where to split string (much as FS can be a regexp describing where to split input records; see Regexp Field Splitting ). if fieldsep is omitted, the value of FS is used. split () returns the number of elements created. seps is a gawk extension with seps [I] being the separator string between array [I] and array [I + 1]. if fieldsep is a single space then any leading whitespace goes into seps [0] and any trailing whitespace goes into seps [n] where n is the return value of split () (that is, the number of elements in array ).

The split () function splits strings into pieces in a manner similar to the way input lines are split into fields. For example:

Split ("cul-de-sac", a, "-", seps)

Splits the string 'cul-de-sac 'into three fields using'-' as the separator. It sets the contents of the array a as follows:

A [1] = "cul"

A [2] = "de"

A [3] = "sac"

And sets the contents of the array seps as follows:

Seps [1] = "-"

Seps [2] = "-"

The value returned by this call to split () is three.

As with input field-splitting, when the value of fieldsep is "", leading and trailing whitespace is ignored in values assigned to the elements of array but not in seps, and the elements are separated by runs of whitespace. also as with input field-splitting, if fieldsep is the null string, each individual character in the string is split into its own array element. (c. e .)

Note, however, that RS has no effect on the way split () works. even though 'rs = "" 'Causes newline to also be an input field separator, this does not affect how split () splits strings.

Modern implementations of awk, including gawk, allow the third argument to be a regexp constant (/abc/) as well as a string. (d.c .) the POSIX standard allows this as well. see Computed Regexps, for a discussion of the difference between using a string constant or a regexp constant, and the implications for writing your program correctly.

Before splitting the string, split () deletes any previusly existing elements in the arrays array and seps.

If string is null, the array has no elements. (So this is a portable way to delete an entire array with one statement. See Delete .)

If string does not match fieldsep at all (but is not null), array has one element only. The value of that element is the original string.

Sprintf (format, expression1 ,...)

Return (without printing) the string that printf wowould have printed out with the same arguments (see Printf). For example:

Pival = sprintf ("pi = %. 2f (approx.)", 22/7)

Assigns the string 'Pi = 3.14 (approx.) 'to the variable pival.

Sub (regexp, replacement [, target])

Search target, which is treated as a string, for the leftmost, longest substring matched by the regular expression regexp. modify the entire string by replacing the matched text with replacement. the modified string becomes the new value of target. return the number of substitutions made (zero or one ).

The regexp argument may be either a regexp constant (/... /) or a string constant ("... "). in the latter case, the string is treated as a regexp to be matched. see Computed Regexps, for a discussion of the difference between the two forms, and the implications for writing your program correctly.

This function is peculiar because target is not simply used to compute a value, and not just any expression will do-it must be a variable, field, or array element so that sub () can store a modified value there. if this argument is omitted, then the default is to use and alter $0.42 For example:

Str = "water, water, everywhere"

Sub (/at/, "ith", str)

Sets str to 'wither, water, everywhere', by replacing the leftmost longest occurrence of 'at' with 'ith '.

If the special character '& 'appears in replacement, it stands for the precise substring that was matched by regexp. (If the regexp can match more than one string, then this precise substring may vary .) for example:

{Sub (/candidate/, "& and his wife"); print}

Changes the first occurrence of 'canonicaldate' to 'canonicaldate' and his ife 'on each input line. Here is another example:

$ Awk 'in in {

> Str = "daabaaa"

> Sub (/a +/, "C & C", str)

> Print str

> }'

-| DCaaCbaaa

This shows how '& 'can represent a nonconstant string and also indexes strates the "leftmost, longest" rule in regexp matching (see Leftmost Longest ).

The effect of this special character ('&') can be turned off by putting a backslash before it in the string. as usual, to insert one backslash in the string, you must write two backslashes. therefore, write' \ & 'in a string constant to include a literal' &' in the replacement. for example, the following shows how to replace the first '|' on each line with '&':

{Sub (/\ |/, "\ &"); print}

As mentioned, the third argument to sub () must be a variable, field or array element. some versions of awk allow the third argument to be an expression that is not an lvalue. in such a case, sub () still searches for the pattern and returns zero or one, but the result of the substitution (if any) is thrown away because there is no place to put it. such versions of awk accept expressions like the following:

Sub (/USA/, "United States", "the USA and Canada ")

For historical compatibility, gawk accepts such erroneous code. However, using any other nonchangeable object as the third parameter causes a fatal error and your program will not run.

Finally, if the regexp is not a regexp constant, it is converted into a string, and then the value of that string is treated as the regexp to match.

Substr (string, start [, length])

Return a length-character-long substring of string, starting at character number start. the first character of a string is character number one.43 For example, substr ("washington", 5, 3) returns "ing ".

If length is not present, substr () returns the whole suffix of string that begins at character number start. for example, substr ("washington", 5) returns "ington ". the whole suffix is also returned if length is greater than the number of characters remaining in the string, counting from character start.

If start is less than one, substr () treats it as if it was one. (POSIX doesn't specify what to do in this case: Brian Kernighan's awk acts this way, and therefore gawk does too .) if start is greater than the number of characters in the string, substr () returns the null string. similarly, if length is present but less than or equal to zero, the null string is returned.

The string returned by substr () cannot be assigned. Thus, it is a mistake to attempt to change a portion of a string, as shown in the following example:

String = "abcdef"

# Try to get "abCDEf", won't work

Substr (string, 3, 3) = "CDE"

It is also a mistake to use substr () as the third argument of sub () or gsub ():

Gsub (/xyz/, "pdq", substr ($0, 5, 20) # WRONG

(Some required cial versions of awk treat substr () as assignable, but doing so is not portable .)

If you need to replace bits and pieces of a string, combine substr () with string concatenation, in the following manner:

String = "abcdef"

String = substr (string, 1, 2) "CDE" substr (string, 6)

Tolower (string)

Return a copy of string, with each uppercase character in the string replaced with its corresponding lowercase character. nonalphabetic characters are left unchanged. for example, tolower ("MiXeD cAsE 123") returns "mixed case 123 ".

Toupper (string)

Return a copy of string, with each lowercase character in the string replaced with its corresponding uppercase character. nonalphabetic characters are left unchanged. for example, toupper ("MiXeD cAsE 123") returns "mixed case 123 ".

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.