简体   繁体   English

AWK拆分字符串并进行比较

[英]Awk splitting a string and comparison

I have a string like AS|REQ|XYZ|value=12 which I am splitting with: 我有一个像AS|REQ|XYZ|value=12这样的字符串,该字符串与之分割:

awk -F\| 'print {$4}' | awk -F"=" '{print $2}'

This gives the value 12. 得出值12。

But for the string DF|REG|EXP|value= , it comes back blank. 但是对于字符串DF|REG|EXP|value= ,它返回空白。

What I need as if my string encounters value in fourth column and is blank, throw error. 我需要的字符串好像在第四列中遇到value并且为空白,引发错误。 Can this be done in awk command ? 可以在awk命令中完成吗?

Thanks 谢谢

You could be more specific about what you mean by throwing an error . 通过抛出错误,您可以更具体地说明您的意思。 If you want the program to exit with a non-zero exit code, use if and exit with value`: 如果您希望程序以非零的退出代码退出,请使用if并以value` exit

$ awk 'BEGIN{exit}'
$ echo $?
0
$ awk 'BEGIN{exit 1}'
$ echo $?
1
$ awk -F\| '{split($4,a,"="); if(a[2]=="") exit 1; else print a[2]}' foo
12
$ echo $?
1

or just print an error message and continue execution: 或仅显示错误消息并继续执行:

$ awk -F\| '{split($4,a,"="); print (a[2]==""?"ERROR":a[2])}' foo
12
ERROR

Test data used above: 上面使用的测试数据:

$ cat foo
AS|REQ|XYZ|value=12
DF|REG|EXP|value=

@JamesBrown has the right answer to your question as asked, but given the input you posted all you need to produce the output you want is: @JamesBrown按照要求对您的问题有正确的答案,但是考虑到您发布的输入,您需要产生的所有输出是:

awk -F'=' '{print ($NF=="" ? "Error" : $NF)}' file

If that's NOT all you need then edit your question to show some more truly representative sample input and expected output. 如果这还不是您所需要的,那么请编辑您的问题,以显示更真实的示例输入和预期输出。

大概是这样吗?

awk -F\| '{print $4}' | awk -F"=" '{if ($2 == "") print "ERROR: Empty Value"; else print $2}'

Hope this command might work for you. 希望此命令对您有用。 The below command will behave as expected. 下面的命令将按预期方式运行。 If you have any value in the value field, it will just print the value. 如果在值字段中有任何值,它将只打印该值。 Else if it is blank, it prints "error". 否则,如果为空,则打印“错误”。 The string was placed in test.txt 字符串被放置在test.txt中

awk -F\| '{if($4!="value=") {gsub("value=","",$4);print $4} else print "error" }' test.txt

Something like this - 像这样-

cat f
AS|REQ|XYZ|value=12
AS|REQ|XYZ|value=

awk -F'[|=]' '{if($4 == "value" && $5 == "") {print ("Error Found at Line: ",NR)} else {print $0}}' f
AS|REQ|XYZ|value=12
Error Found at Line:  2

It search for value in 4th column and blank in 5th column. 4th列中搜索value4th 5th列中搜索blank

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

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