简体   繁体   English

awk命令返回不一致的结果

[英]awk command returns inconsistent result

I have a script which performs several validations in a file. 我有一个脚本,可以在一个文件中执行多个验证。 One of the validation is to check if a line exceeds 95 characters (including spaces). 验证之一是检查一行是否超过95个字符(包括空格)。 If it does, it will return the line number/s where the line exceeds 95 characters. 如果是这样,它将返回行数超过95个字符的行号。 Below is the command used for the validation: 以下是用于验证的命令:

$(cat $FileName > $tempfile)
totalCharacters=$(awk '{print length($0);}' $tempFile | grep -vn [9][4])
if [[$totalCharacters != "" ]]; then
  totalCharacters=$(awk '{print length($0);}' $tempFile | grep -vn [9][4] | cut -d : -f1 | tr "\n" ",")
  echo "line too long"
  exit 1
fi

In the lower environment the code is working as expected. 在较低的环境中,代码按预期工作。 But in production, there are time that the validation returns the error "line too long" but does not return any line number. 但是在生产中,有时验证会返回“行过长”错误,但不会返回任何行号。 We just reran the script and it does not return any error. 我们只是重新运行了脚本,它没有返回任何错误。

I would like to know what could be wrong in the command used. 我想知道所使用的命令中可能有什么问题。 The previous developer who worked on this said that it could be an issue with the use of the awk command, but I am not sure since this is the first time I have encountered using the awk command. 以前从事此工作的开发人员表示,使用awk命令可能会出现问题,但是我不确定,因为这是我第一次使用awk命令。

This is not well written. 这写得不好。 All you need is: 所有你需要的是:

awk 'length>94{print NR; f=1} END{exit f}' file

If there are lines longer than 94 chars, it will print the line numbers and the exit with status 1; 如果行数超过94个字符,它将打印行号和状态为1的退出; otherwise the exit status will be 0 and no output will be generated. 否则,退出状态将为0,并且不会生成任何输出。

Your script should just be: 您的脚本应该只是:

awk '
    length()>95 { printf "%s%d", (c++?",":""), NR }
    END { if (c) {print "line too long"; exit 1} }
' "$FileName"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM