欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

Linux里awk中split函数的用法小结

程序员文章站 2023-11-22 22:59:04
the awk function split(s,a,sep) splits a string s into an awk array a using the delimi...

the awk function split(s,a,sep) splits a string s into an awk array a using the delimiter sep.

set time = 12:34:56
set hr = `echo $time | awk '{split($0,a,":" ); print a[1]}'` # = 12
set sec = `echo $time | awk '{split($0,a,":" ); print a[3]}'` # = 56
# = 12 34 56
set hms = `echo $time | awk '{split($0,a,":" ); print a[1], a[2], a[3]}'`

——————————————————————————————————————————
q:
name="76868&5676&435&43526&334&12312312&12321"
awk 'begin {print split("$name", filearray, "&")}'
为什么是1

awk 'begin {print split("76868&5676&435&43526&334&12312312&12321", filearray, "&")}'
则返回正确的结果,应该是7,有没有人解答一下?

a:
变量引用错误,这样做试试
awk 'begin {print split('"\"$name\""', filearray, "&")}'

awk规定引用系统变量必须使用单引号加双引号,即'"$sysvar"'这样的格式,但是split函数也需要双引号来定界,但这个双引号又不能让sh解释,而应留给awk来解释,所以使用了\"和\"组成的双引号

split函数的用法

he awk function split(s,a,sep) splits a string s into an awk array a using the delimiter sep.
set time = 12:34:56
set hr = `echo $time | awk '{split($0,a,":" ); print a[1]}'` # = 12
set sec = `echo $time | awk '{split($0,a,":" ); print a[3]}'` # = 56

# = 12 34 56
set hms = `echo $time | awk '{split($0,a,":" ); print a[1], a[2], a[3]}'`
set hms = `echo $time | awk '{split($0,a,":" ); for (i=1; i<=3; i++) print a[i]}'`

实例一:

cat a
a:b:c:d:e:f:g:h:i
使用awk将该字符串冒号两边的段输出
cat a |awk -f':' '{split($0,arr,":")}end{for(i=1;i<=nf;i++)printf("%s\n",arr[i])}'
输出结果如下
a

c
d
e
f
g
h
i