I have a string like AS|REQ|XYZ|value=12
which I am splitting with:
awk -F\| 'print {$4}' | awk -F"=" '{print $2}'
This gives the value 12.
But for the string DF|REG|EXP|value=
, it comes back blank.
What I need as if my string encounters value
in fourth column and is blank, throw error. Can this be done in awk command ?
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`:
$ 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:
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.