当字符串中包含管道符号|时,如何拆分字符串。 我想把它们分割成数组。
我试着
echo "12:23:11" | awk '{split($0,a,":"); print a[3] a[2] a[1]}'
这很好。如果我的字符串是像“12|23|11”,那么我如何把它们分割成一个数组?
当字符串中包含管道符号|时,如何拆分字符串。 我想把它们分割成数组。
我试着
echo "12:23:11" | awk '{split($0,a,":"); print a[3] a[2] a[1]}'
这很好。如果我的字符串是像“12|23|11”,那么我如何把它们分割成一个数组?
当前回答
在awk中,我们使用split()函数将字符串拆分为数组:
awk '{split($0, array, ":")}'
# \/ \___/ \_/
# | | |
# string | delimiter
# |
# array to store the pieces
如果没有指定分隔符,则使用FS,默认为空格:
$ awk '{split($0, array); print array[2]}' <<< "a:b c:d e"
c:d
我们可以给出一个分隔符,例如::
$ awk '{split($0, array, ":"); print array[2]}' <<< "a:b c:d e"
b c
这相当于通过FS设置:
$ awk -F: '{split($0, array); print array[2]}' <<< "a:b c:d e"
b c
在GNU Awk中,你也可以提供分隔符作为regexp:
$ awk '{split($0, array, ":*"); print array[2]}' <<< "a:::b c::d e
#note multiple :
b c
甚至可以通过使用第四个参数来查看每一步的分隔符:
$ awk '{split($0, array, ":*", sep); print array[2]; print sep[1]}' <<< "a:::b c::d e"
b c
:::
让我们引用GNU awk的手册页:
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). 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() (i.e., the number of elements in array).
其他回答
code
awk -F"|" '{split($0,a); print a[1],a[2],a[3]}' <<< '12|23|11'
输出
12 23 11
echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
你有没有试过:
echo "12|23|11" | awk '{split($0,a,"|"); print a[3],a[2],a[1]}'
awk -F'['|'] -v '{print $1"\t"$2"\t"$3}' file <<<'12|23|11'
我知道这是个老问题,但我想也许有人喜欢我的把戏。特别是因为这个解决方案不局限于特定数量的项目。
# Convert to an array
_ITEMS=($(echo "12|23|11" | tr '|' '\n'))
# Output array items
for _ITEM in "${_ITEMS[@]}"; do
echo "Item: ${_ITEM}"
done
输出将是:
Item: 12
Item: 23
Item: 11