Reputation: 640
I have logs in below format, I am trying to grep multiple fields from them.
2020-09-23 INFO [http-nio-8080-exec-428] localhost.com CLIENT_ID=abc CLIENT_IP=1.2.3 CLASS_NAME=ABCIMPL METHOD_NAME=789{Roles} REQUEST=[<Request>
some text
</Request>
2020-09-23 INFO [http-nio-8080-exec-428] localhost.com CLIENT_ID=mno CLIENT_IP=1.2.4 CLASS_NAME=MNOP METHOD_NAME=1234{Decisions} REQUEST=[<Request>
some text
</Request>
I want to capture 3 fields in a text file in below format.
CLIENT_ID=abc , CLASS_NAME=ABCIMPL , METHOD_NAME=789{Roles}
CLIENT_ID=mno , CLASS_NAME=MNOP , METHOD_NAME=1234{Decisions}
I am able to capture one field but not all of them.
Regards
Upvotes: 0
Views: 125
Reputation: 103754
You can use sed
to capture the fields of interest:
sed -nE 's/.* (CLIENT_ID=[^[:space:]]*).* (CLASS_NAME=[^[:space:]]*).* (METHOD_NAME=[^[:space:]]*).*/\1, \2, \3/p' file
CLIENT_ID=abc, CLASS_NAME=ABCIMPL, METHOD_NAME=789{Roles}
CLIENT_ID=mno, CLASS_NAME=MNOP, METHOD_NAME=1234{Decisions}
Upvotes: 4
Reputation: 784998
Since it is log file, your field positions are fixed. You can use this simple awk:
awk -v OFS=' , ' '$1 ~ /^[0-9]{4}(-[0-9]{2}){2}$/{ print $5, $6, $8}' file.log
CLIENT_ID=abc , CLIENT_IP=1.2.3 , METHOD_NAME=789{Roles}
CLIENT_ID=mno , CLIENT_IP=1.2.4 , METHOD_NAME=1234{Decisions}
Upvotes: 3
Reputation: 5965
You can use this awk script. You can define any patterns for printing and their separator. Also I match a date at the beginning of lines in interest, you could also modify that to your requirements if it is not enough.
BEGIN { p["CLIENT_ID="]; p["CLASS_NAME="]; p["METHOD_NAME="] }
/^[0-9]{4}-[0-9]{2}-[0-9]{2}/ {
r = ""
for (i=1;i<=NF;i++) for (x in p) if ($i ~ x) r = r? r ", " $i: $i
print r
}
Usage:
> awk -f tst.awk file
CLIENT_ID=abc, CLASS_NAME=ABCIMPL, METHOD_NAME=789{Roles}
CLIENT_ID=mno, CLASS_NAME=MNOP, METHOD_NAME=1234{Decisions}
Upvotes: 2
Reputation: 133458
Could you please try following, written and tested with shown samples in GNU awk
.
awk '
BEGIN{
OFS=" , "
}
match($0,/CLIENT_ID[^ ]*/){
val=substr($0,RSTART,RLENGTH)
match($0,/CLASS_NAME[^ ]*/)
val1=substr($0,RSTART,RLENGTH)
match($0,/METHOD_NAME[^ ]*/)
print val,val1,substr($0,RSTART,RLENGTH)
val=val1=""
}' Input_file
Upvotes: 3