The company does the statistical extraction Field Service is C compiles the bin file, often core dump causes the machine hangs up, deeply its bitter, has written a shell version as the substitution.
Originally intended to be implemented in awk,
Awk-f "[=]" ' {Do something} '
In this way, but the log field is not fixed (may appear, may not appear), not very good implementation, it should use grep, every two fields appear before and after the order is fixed.
The script is as follows (get_fields.sh):
#! /bin/bash
#set
-X # The default delimiter
fs= "
ret=" "
# Get options while
getopts f:k: Opt
the "$opt" in
F)
fs= $OPTARG;;
k)
keys= $OPTARG;;
Esac
do
# split string into an array
keys= (${keys//,/})
num=${#keys [@]}
if [$num-eq 0];
then
echo "not enough parameter";
Exit;
Fi while
read line
do
retstr= ""
found=0 to
key in ${keys[@]}
do
# \bxxx:word Start by xxx
tmpstr= ' echo ${line} | grep-oe ' \b${key}=[^${fs}]* ' ' # did ' when ', ' not '
empty
[-N "${tmpstr}"] && Retstr=${retstr}${tmpstr}${fs} && let found+=1
done
# Check num
[-n ' ${ RETSTR} "-A $found-eq $num] && echo-e ${retstr}" \ n "| Sed '/^$/d ' done
Use instance:
Test.log:
A=1 b=2 c=3 D=a
To extract the A,c two fields:
Cat Test.log | SH get_fields.sh-f ""-K A,c
Results:
A=1 c=3
Finally, thank Yajie for the technical support of getopts. Thanks for the 30 minute introductory tutorial.
------------
Update:
On the Chinaunix posted, asked the question, Daniel's answer too to the force ...
Address: http://bbs.chinaunix.net/thread-4169843-1-1.html
In the end, I used awk:
Cat Test.log | Grep-e "\bname" | awk ' {for (i=1;i<=nf;i++) s= ($i ~/^name=|^pc=/)? s "\ T" $i: s;$0=s;s= ""}nf+=0 "