file:
timestamp1 KKIE ABC=123 [5454] GHI=547 JKL=877 MNO=878
timestamp2 GGHI ABC=544 [ 24548] GHI=883 JKL=587 MNO=874
timestamp3 GGGIO ABC=877 [3487] GHI=77422 JKL=877 MNO=877
timestamp4 GGDI ABC=269 [ 1896] GHI=887 JKL=877 MNO=123
note: You sometimes have a space between '[' and the next digit).
when JKL=877, I want timestampx, ABC and GHI
solution 1:
timestamp1 ABC=123 GHI=547
timestamp3 ABC=877 GHI=77422
timestamp4 ABC=269 GHI=887
solution 2 (the best one):
TIMESTAMP ABC GHI
timestamp1 123 547
timestamp3 877 77422
timestamp4 269 887
I know how to have these values individually but not all of them in once.
A. solution 1:
grep JKL=877 file | awk '{print $1}'
grep JKL=877 file | grep -o '.ABC=[0-9]\{3\}'
grep JKL=877 file | grep -o '.GHI=[0-9]\{3,5\}'
without the '[' issue, I would do:
grep JKL=877 | awk '{print $1,$3,$5}' file
B. for solution 2:
grep JKL=877 file | grep -o '.ABC=[0-9]\{3\}' | tr 'ABC=' ' ' | awk '{print $1}'
(I use awk to remove the space created by tr function)
grep JKL=877 file | grep -o '.GHI=[0-9]\{3,5\}' | tr 'ABC=' ' ' | awk '{print $1}'
without the '[' issue, I would do:
printf "TIMESTAMP ABC GHI\n";
awk '{print $1,$3,$5}' file | tr 'ABC=' ' ' | tr 'GHI=' ' '
C. Now to have them all in once, I was thinking of a loop and puting matches in a variable (see https://unix.stackexchange.com/questions/37313/how-do-i-grep-for-multiple-patterns):
MATCH=".ABC=[0-9]\{3\} .GHI=[0-9]\{3,5\}"
but something is wrong with my syntax; furthermore, it does not include timestampx.
printf "TIMESTAMP ABC GHI\n"
grep JKL=877 file | while read line
do
?
done
Thanx for your help.
Try using sed
printf "TIMESTAMP\tABC\tGHI\n"
sed -nr '/JKL=877/s/^(\w+).*ABC=([0-9]+).*GHI=([0-9]+).*/\1\t\2\t\3/p' file
Output:
TIMESTAMP ABC GHI
timestamp1 123 547
timestamp3 877 77422
timestamp4 269 887
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With