3

I have a script called foo.sh that contains something like

exec myapp -o size=100m -f 

Any idea how to create another script that parses foo.sh and retrieves the value of size? One can assume myapp only appears once in foo.sh, but the order of size argument can appear anywhere in the argument list

Thanks

3 Answers 3

2

With in a shell :

$ grep -oP 'myapp.*?size=\K\d+m' foo.sh
100m

With in a shell :

$ awk -F'size='  '{sub(/ -f/, "");print $2}' foo.sh
100m

or

$ awk '{print gensub(/.*size=([0-9]+m).*/, "\\1", $0)}' foo.sh
100m

With in a shell :

$ perl -lne 'print $1 if /exec.*?size=(\d+m)/' foo.sh
100m

Or using a shell funny trick :

$ declare $(grep -oP "\b\w+=\w+\b" foo.sh)
$ echo $size
100m
Sign up to request clarification or add additional context in comments.

1 Comment

What a nice set of options!
0
cat foo.sh | egrep -o 'size=[[:digit:]]+' | awk -F= '{print $2}'

2 Comments

this almost works. I was hoping to get everything between 'size=' and the next space character
cat | grep | awk is a useless use of cat & grep. partmaps.org/era/unix/award.html#cat
0

A variation on the sed approach. This one short-circuits once it's found the line. Useful if the file is very long and the target is likely near the beginning.

sed  -ne '/exec myapp -o size=/{s/[^0-9]*\([m0-9]*\).*/\1/;p;q;}'

Once it finds the correct line, it extracts the size value, prints it, and then quits.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.