循环遍历文件以计算字段编号 [英] Loop through file to count field number
问题描述
我有一个脚本bash可以从.txt文件中添加用户. 真的很简单:
I have a script bash to add users from a .txt file. It is really simple:
name firstname uid gid
以空格分隔的值
我想用awk检查每一行是否包含4个字段.如果是,我想返回1,如果不是,则返回0.
I want to check with awk if each row contains 4 fields. If yes I want to return 1, if not return 0.
file=/my/file.txt
awk=$(awk -F' ' '{(NF != 4) ? res = 0 : res = 1; print res)}' $file)
echo $awk
现在,awk为每一行返回1,但是我希望它在结尾处返回1或0,而不是文件中的每一行.
Right now, awk returns 1 for each row, but I want it to return 1 or 0 at the end, not for each line in the file.
推荐答案
在UNIX上,如果成功则返回0
,如果出错则返回!=0
.对我来说,当所有记录都具有4
字段时返回0
更有意义,而当并非所有记录都具有4个字段时返回1
更有意义.
On UNIX you'll return 0
in case of success and !=0
in case of an error. For me it makes more sense to return 0
when all records have 4
fields and 1
when not all records have 4 fields.
要实现此目的,请使用 exit
:
To achieve that, use exit
:
awk 'NF!=4{exit 1}' file
仅供参考:默认情况下,awk
将以0
退出.
FYI: awk
will exit with 0
by default.
如果要在有条件的shell中使用它:
If you want to use it in a shell conditional:
#!/bin/bash
if ! awk 'NF!=4{exit 1}' file ; then
echo "file is invalid"
fi
PS:您的示例中的-F' '
是多余的,因为' '
是默认字段定界符.
PS: -F' '
in your example is superfluous because ' '
is the default field delimiter.
这篇关于循环遍历文件以计算字段编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!