TonyL2ca
TonyL2ca

Reputation: 45

find a option in string split by space in bash

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?

Upvotes: 2

Views: 169

Answers (4)

Timmah
Timmah

Reputation: 2121

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.

Upvotes: 1

anishsane
anishsane

Reputation: 20980

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

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77105

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

Upvotes: 1

anubhava
anubhava

Reputation: 785156

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

Upvotes: 2

Related Questions