Search for key value pair from the string and output only the matching record

1k views Asked by At

I have a large file in terms of a string containing key value pairs. I am looking for a proper way to search for the value pair where the value is 'apple' (can be both upper or lower) and output only related key value pair if found.

For ex. 55=APPLE

<SOH> is the delimiter here.

 8=FIX.4.2<SOH>9=153<SOH>35=D<SOH>49=BLP<SOH>56=SCHB<SOH>34=1<SOH>50=30737<SOH>97=Y<SOH>52=20000809-20:20:50<SOH>11=90001008<SOH>1=10030003<SOH>21=2<SOH>55=APPLE<SOH>54=1<SOH>38=4000<SOH>40=2<SOH>59=0<SOH>44=30<SOH>47=I<SOH>60=20000809-18:20:32<SOH>10=061<SOH>

Glad if you could provide any suggestions.

5

There are 5 answers

0
l'L'l On BEST ANSWER

You could use a character class for the digits followed by the = and keyword in the pattern:

 grep -io "[0-9]*=apple" file
  • -i, --ignore-case
  • -o, --only-matching
  • [0-9] a single character in the range between 0 and 9
  • Quantifier: * Between zero and unlimited times,
  • =apple matches the characters =apple literally (case insensitive)
0
Cyrus On

Try this with GNU grep:

grep -ioP '>\K[^=]+=apple(?=<)' file

Output:

55=APPLE
0
NeronLeVelu On

Wihtout more information on real wanted info:

Return the count of line (so 0 if no presence)

grep -i -E -c -e '(^|<SOH>)[^=]*=APPLE<SOH>'

Assuming:

  • <SOH> is a end delimiter
  • you want only APPLE not word/pattern that contain apple
0
luukvhoudt On

Use one of these proper solutions to convert your string into an array so you can itterate through all items. While doing that check the value of the item by using a if string comparison.

if [ "$value" = "APPLE" ]; then
     # do stuff
fi
0
Arjun Mathew Dan On

With awk:

awk -v RS="<SOH>" 'toupper($0)~/APPLE/' File

Set <SOH> as the record seperator. Then check is any record matches with APPLE (to make it case insensitive, converted record to uppercase first), if matched, print the record.