使用awk
逐个字符地解析命令行中的字符串:
echo "foo" | awk 'BEGIN { FS = "" }{ for (n=1; n<=NF; n++ ) print $n }'
工作正常。我们还可以在命令行上设置FS的值。但是这个:
echo "foo" | awk -F '' '{ for (n=1; n<=NF; n++ ) print $n }'
产生以下错误消息:
awk: field separator FS is empty
为什么两种方法都不会返回相同的结果?
重要:GNU bash,版本3.2.57(1)-release(x86_64-apple-darwin14)
答案 0 :(得分:0)
更新 awk 的版本?
$ bash --version | head -n1
GNU bash, version 4.3.42(1)-release (x86_64-pc-linux-gnu)
$ gawk --version | head -n 1
GNU Awk 4.1.1, API: 1.1 (GNU MPFR 3.1.3, GNU MP 6.0.0)
$ mawk -W version
mawk 1.3.3 Nov 1996, Copyright (C) Michael D. Brennan
compiled limits:
max NF 32767
sprintf buffer 2040
$ echo "foo" | gawk -F '' '{ for (n=1; n<=NF; n++ ) print $n }'
f
o
o
$ echo "foo" | mawk -F '' '{ for (n=1; n<=NF; n++ ) print $n }'
f
o
o
$ echo "foo" | gawk 'BEGIN { FS = "" }{ for (n=1; n<=NF; n++ ) print $n }'
f
o
o
$ echo "foo" | mawk 'BEGIN { FS = "" }{ for (n=1; n<=NF; n++ ) print $n }'
f
o
o