Share a script that extracts fields

Source: Internet
Author: User

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 "




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.