2

I have a string like this, name it Options:

"printer-is-accepting-jobs=true printer-is-shared=false printer-location=Library printer-make-and-model='HP LaserJet 600 M601 M602 M603' printer-state=3"

they are "options=values" format, separated by spaces. but the "printer-make-and-model" has value with spaces.

tried command:

for word in $Options; do echo $word; done

all the HP LaserJet 600 M601 M602 M603 are splited.

How to deal with this in bash command?

jaypal singh
  • 74,723
  • 23
  • 102
  • 147
TonyL2ca
  • 45
  • 5

4 Answers4

2

Using grep -oP:

grep -oP "printer-make-and-model='\K[^']*" <<< "$s"
HP LaserJet 600 M601 M602 M603

OR using sed:

sed "s/^.*printer-make-and-model='\([^']*\).*/\1/" <<< "$s"
HP LaserJet 600 M601 M602 M603
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

Anubhava's regex is good, so if you don't have grep -P option then you can try:

ack command:

$ ack -ho "printer-make-and-model='\K[^']*" <<< "$options"
HP LaserJet 600 M601 M602 M603

or Perl:

$ perl -nle "print $+{f} if /printer-make-and-model='(?'f'\K[^']*)/" <<< "$options"
HP LaserJet 600 M601 M602 M603
Community
  • 1
  • 1
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
1

You can do this with multiple awk statements:

while read record; do
    while read key value; do
        echo "K=($key) V=($value)"
    done< <(awk -F"=" '{printf("%s %s\n", $1, $2)}' <<< $record)
done< <(awk -F"printer-" '{for(i=2;i<NF;i++){printf("printer-%s\n", $i)}}' <<< $string)

This will split to output into key value pairs.

Timmah
  • 2,001
  • 19
  • 18
0

Since you need to parse options, you can use getopt. However, this requires to use the evil eval command. So be careful about your input.

$ string="printer-is-accepting-jobs=true printer-is-shared=false printer-location=Library printer-make-and-model='HP LaserJet 600 M601 M602 M603' printer-state=3"
$ eval a=("$string")
$ eval b=($(getopt --long printer-make-and-model: -- ${a[@]/#/--} 2>/dev/null))
$ echo "${b[1]}"
HP LaserJet 600 M601 M602 M603
anishsane
  • 20,270
  • 5
  • 40
  • 73
  • on my Mac, **echo "${b[1]}"** gets **"printer-make-and-model:"** – TonyL2ca Feb 28 '14 at 23:10
  • Frankly, I haven't tried it on mac, but I think, `getopt` on `mac` gives different output than on my system. try `for x in "${b[@]}; do echo $x; done` to see if the order of parameters has changed in the getopt output... – anishsane Mar 03 '14 at 05:22