phonedog365
phonedog365

Reputation: 69

Extracting values between keys using sed

I'm trying to extract the value of keys entered as options for a command-line bash script and failing.

I've tried matching regex with grep and sed both with and without the -E option. I can get a grep to work extracting keys from the initial command input:

grep -wo -- "-[^ ]*"

Works to extract keys from the command line that have "-" or "--" format, but I need the values between two keys or from a key to the end of line if there's no additional key(s).

key="-r"
input="command -r root1 root2 -s ip"

echo $input | sed "s/^.*$key \([^-]\+\)\( -.\+$\|$\)/$key has value \1/g;"

Output:

command -r root1 root2 -s ip

Expected output:

root1 root2

Clearly, \1 is matching the whole line, but I just need the contents of the input line from the $key to the next key or the end of line. Any assistance would be appreciated.

Upvotes: 0

Views: 266

Answers (2)

potong
potong

Reputation: 58391

This might work for you (GNU sed):

key='-r'
sed -En 's/ -\w */\n&/g;s/.*\n '$key' *([^\n]*).*/\1/p' file

Prefix each option by a newline and then extract the required option up and until the next newline.

Upvotes: 0

phonedog365
phonedog365

Reputation: 69

Figured it out with some examples from the "possible duplicate" comment.

key="-a";
input="command -a option1 option2 -r root1 root2 -s ip ip ip";
echo $input | sed -E "s/^.*$key ([^-]*)(-.*$|$)/\1/g;"

produces the desired "option1 option 2" output. I think sed wasn't liking my \(..\|..\) clause. Switched to sed -E and removed the backslashes and it's working.

Thanks for the assist.

Upvotes: 1

Related Questions