问题描述
我正在处理一个文件,其中字段由单个空格分隔.
I am dealing with a file where fields are separated by a single space.
awk将FS " "
解释为一个或多个空格",当其中一个字段为空时,它将错误读取我的文件.
awk interprets the FS " "
as "one or more whitespace", which misreads my file when one of the fields is empty.
我尝试使用空格后不加空格"(" (?! )"
)作为FS,但是awk不支持否定的超前.简单的Google查询(例如单个空格分隔符awk")仅将我带到手册页,解释了FS=" "
的特殊处理.我一定错过了相关的手册页...
I tried using "a space not followed by a space"( " (?! )"
) as FS but awk does not support negative lookahead. Simple google queries like "single space field separator awk" only sent me to the manual page explaining the special treatment of FS=" "
. I must have missed the relevant manual page...
如何在awk中使用单个空格作为字段分隔符?
How can I use a single space as field separator with awk?
推荐答案
这应该有效
$ echo 'a b' | awk -F'[ ]' '{print NF}'
5
其中,这会将所有连续的空白都视为一个空白.
where as, this treats all contiguous white space as one.
$ echo 'a b' | awk -F' ' '{print NF}'
2
基于注释,需要特别考虑,空字符串或空格,因为字段值是非常不同的东西,可能与空格分隔的内容不太匹配.
based on the comment, it need special consideration, empty string or white space as field value are very different things probably not a good match for a white space separated content.
例如,建议使用cut
进行预处理并更改定界符
I would suggest preprocessing with cut
and changing the delimiters, for example
$ echo 'a b' | cut -d' ' -f1,3,5 --output-delimiter=,
a,,b
这篇关于单个空间作为带awk的字段分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!