awk常用字符串处理函数

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 'BEGIN { print index("peanut", "an") }'

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 could 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 'BEGIN { print length(x) ; x[1] = 1 }'

          error--> gawk: fatal: attempt to use scalar `x' as array

          $ nawk 'BEGIN { 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 the ‘~’ 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 at",

                               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 should 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 previously 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 would 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 ‘candidate’ to ‘candidate and his wife’ on each input line. Here is another example:

          $ awk 'BEGIN {

          >         str = "daabaaa"

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

          >         print str

          > }'

          -| dCaaCbaaa

This shows how ‘&’ can represent a nonconstant string and also illustrates 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 an ‘&’:

          { 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 commercial 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".

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: AWK 是一种强大的文本处理工具,它提供了切割字符串的功能。你可以使用内置的函数 substr() 和 split() 对字符串进行切割。你也可以使用正则表达式来提取你需要的部分。 例如,下面是使用 substr() 函数切割字符串的例子: ``` awk '{print substr($0, 1, 5)}' inputfile ``` 这段代码会输出输入文件中每一行的前 5 个字符。 更多关于 AWK 切割字符串的细节,请参考 AWK 的文档或者相关书籍。 ### 回答2: Shell是一种脚本语言,在Linux和类Unix操作系统上非常流行。通过使用Shell脚本,可以轻松地执行各种任务和自动化工作。其中,Shell命令awk是一款非常强大的工具,可以用来切割字符串,进行文本处理,并对文本进行格式化输出。 awk是一种基于行的文本处理工具,最主要的功能是文本分割和格式化输出。其中,使用awk进行字符串的切割是其非常重要和常用的功能。在Shell中,可以通过使用awk命令进行字符串的切割,同时也可以对切割出的字符串进行格式化输出。 具体来看,awk命令可以用以下格式进行使用: awk 'BEGIN {表达式} {action} END {表达式}' file 在这个命令中,BEGIN和END是可选的,它们用来设计在awk开始处理数据前和结束处理数据后执行的动作。其中,表达式可以是任何有效的awk表达式,而action则是对每行数据进行处理的动作。 当使用awk进行字符串切割时,需要使用内置的分隔符FS(Field Separator),默认情况下FS是空格或Tab键。通过设置FS,可以让awk定位到需要操作的字段,然后将其切割出来。此外,还可以使用$符号来定位到每个字段,其中$0代表整行数据,$1代表第一个字段,$2代表第二个字段,以此类推。 例如,如果需要将以下数据对每个字段进行切割,并输出第二个和第三个字段,则可以使用以下awk命令: cat file.txt | awk -F "\t" '{print $2,$3}' 在这个命令中,-F "\t"指定分隔符为Tab键,而{print $2,$3}则是输出第二个和第三个字段。通过这样的方式,可以快速、方便地对字符串进行切割和处理。 总而言之,awk命令是Shell中非常重要和实用的工具,可以用来进行字符串的切割、文本处理和格式化输出等任务。通过灵活地使用awk命令和其内置的分隔符,可以轻松地完成各种文本处理任务,提高工作效率和准确性。 ### 回答3: Shell和awk都是常用的文本处理工具,在处理文本中的字符串时,常常需要对字符串进行切割、格式化等操作。本文将简单介绍如何使用Shell和awk切割字符串。 一、Shell中的字符串切割 在Shell中,字符串可以看作是一种特殊的变量类型。可以通过变量名来访问字符串中的每一个字符,如下所示: str="hello,world" echo "第二个字符是:${str:1:1}" 上述代码中,使用冒号分隔符来对字符串进行切割,第一个数字表示从字符串的第几个字符开始切割,第二个数字表示切割的长度。 另外,在Shell中也可以通过sed、cut等命令来对字符串进行切割。如下所示: str="hello,world" echo $str | cut -d "," -f 1 上述代码使用了cut命令,将字符串以逗号作为分隔符进行切割,然后输出第一部分。 二、awk中的字符串切割 awk是一种强大的文本处理工具,可以对文本进行高效的处理。在awk中,可以通过$符号访问每个输入的字段,可以结合正则表达式来进行字符串的切割和匹配。 以下是一个简单的例子: echo "hello,world" | awk -F, '{print $1}' 上述代码中,使用了-F选项来指定逗号为分隔符,然后输出第一个字段。 awk还支持sub和gsub函数,可以用来替换字符串中的特定字符。如下所示: echo "hello,world" | awk '{gsub(/o/,"O",$1);print $1}' 上述代码将$1字段中的所有o字符替换成O,然后输出修改后的内容。 总结: Shell和awk是文本处理的常用工具,字符串切割是文本处理中常用的操作之一。本文介绍了在Shell和awk中如何对字符串进行切割和处理,希望对读者有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值