0

I have a line with:

-Dapp.id=XXX -Dapp.name=YYY -Dapp.inventory.id=KKK -Dapp.inventory1.id=UNDEFINED -app.id=MMM

in an inventory.txt file. If I use the grep statement below, I get the entire line instead of only KKK:

grep -F app.inventory.id= /cme/apps/install/*/inventory/*.txt

I also tried flags like -Fx and -w, but nothing works. How can I get the just KKK using grep?

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • I know this is a crappy thing to say, but use `sed` or `awk` instead. It will let you control which part gets printed. `grep` will too with the `-o`, but it will include the `-D...` part too. – Mad Physicist Mar 21 '16 at 15:25
  • 1
    you can use the option : grep -o – Ali ISSA Mar 21 '16 at 16:00

6 Answers6

0

If you want to do this with just grep, you can use a grep with the PCRE library built in. For example:

$ pcregrep -o 'app.inventory.id=\K[^[:space:]]+' /tmp/corpus
KKK

Alternatively, if you don't have PCRE available you can use grep with extended regular expressions, and then use cut to get the correct field by using = as a field delimiter. For example:

$ grep -Eo 'app.inventory.id=\K[^[:space:]]+' /tmp/corpus | cut -d= -f2
KKK
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
0

if all the files have same types of output wich means :

-Dapp.id=VALUE -Dapp.name=VALUE -Dapp.inventory.id=VALUE -Dapp.inventory1.id=VALUE [...]

You can then use awk like this :

grep -F app.inventory.id= /cme/apps/install/*/inventory/*.txt | awk -F ' ' '{print $3}' | awk -F '=' '{print $2}
rsabir
  • 738
  • 1
  • 7
  • 17
0

I think sed is a bit nicer here:

sed -n 's/.*-Dapp.inventory.id=\([^ ]*\).*/\1/gp' /cme/apps/install/*/inventory/*.txt

If you want the filename you can do something like

for filename in /cme/apps/install/*/inventory/*.txt; do 
    sed -n -e 's/.*-Dapp.inventory.id=\([^ ]*\).*/'$filename': \1/gp' $filename; 
done
chthonicdaemon
  • 19,180
  • 2
  • 52
  • 66
0

grep -Eo "\s-Dapp.inventory.id=[A-Z]+\s" inventory.txt | cut -d '=' -f2

grep

  • -E use extended regex,
  • -o output only the match
  • [A-Z]+\s matches Uppercase-Letters to the next whitespace

To see the match: grep --color -Eo "\s-Dapp.inventory.id=[A-Z]+\s" inventory.txt

cut

  • -d --delimiter=DELIM delimiter of fields,
  • -f --fields=LIST output only the selected fields
pce
  • 5,571
  • 2
  • 20
  • 25
0

awk to the rescue!

$ echo -Dapp.id=XXX -Dapp.name=YYY -Dapp.inventory.id=KKK -Dapp.inventory1.id=UNDEFINED -app.id=MMM | 
  awk -v RS=' +' '/app.inventory.id/{split($0,a,"=");print a[2]}'

KKK
karakfa
  • 66,216
  • 7
  • 41
  • 56
0
awk -F '[= ]' '{print $6}' file
KKK
Claes Wikner
  • 1,457
  • 1
  • 9
  • 8