Ifechi
Ifechi

Reputation: 117

Extracting specific strings from a file using bash script

I want to extract certain strings and their values from a log file having text as below using bash code;

key=DATA&channel=WEB&number=234xxxxxxxxxx
state=MOB&dest=3000&key=SMS&number=234xxxxxxxxxxx

The desired result should be;

key=DATA number=234xxxxxxxxxx
key=SMS  number=234xxxxxxxxxx

Thanks.

Upvotes: 0

Views: 75

Answers (3)

Jotne
Jotne

Reputation: 41456

This should do:

awk -F\& '{print $1,$NF}' file
key=DATA number=234xxxxxxxxxx
state=MOB number=234xxxxxxxxxxx

Separate data with &, then just print first and last field.

Upvotes: 0

David C. Rankin
David C. Rankin

Reputation: 84561

You can also do it with read and printf from the command line using parameter expansion/substring extraction:

$ ( while read -r line; do printf "%-10s  %s\n" "${line%%&*}" "${line##*&}"; done < dat/keyval.log )
key=DATA    number=234xxxxxxxxxx
state=MOB   number=234xxxxxxxxxxx

note: run in a subshell above, but you can run it without the subshell as well.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

You could use grep.

grep -o '\b\(key\|number\)=[^&]*' file | paste - -

OR

awk -F'&' '{for(i=1;i<=NF;i++)if($i~/^key|number/) print $i}' file | paste - -

Upvotes: 2

Related Questions