extract value of an assignment expression

1.3k views Asked by At

Suppose I have this string:

a b c d e=x f g h i

What's the best* way to extract the value x from e=x using only Linux commands (like sed and awk)?

*The definition of "best" is up to you.

8

There are 8 answers

0
mohit6up On

Will grep do? Assuming I understand your question correctly:

echo $s | grep -oP '(?<=e\=)[^ ]*'

where s='a b c d e=x f g h i'

0
Dr. belisarius On

gAWK

/=/ {match($0, /\<\w+=\w+\>/, a);print a[0]}
0
kurumi On

If you Linux system have Ruby

$ echo 'a b c d e=x f g h i' | ruby -e 'puts gets.scan(/=(\w+)/)[0][0]'
x

or alternative

$ echo 'a b c d e=x f g h i'| tr "=" "\n"| awk 'NR==2{print $1}'
x
0
phemmer On

An all bash solution which can handle all those variables (not sure of the ultimate goal of this) cleanly

STRING="a b c d e=x f g h i"
export IFS="="
while read -d ' ' var value; do
 echo "$var is $value"
done <<< "$STRING"
0
William Pursell On

With a modern perl:

$ perl -nE 'm/e=(\S*)/; say $1'

or

$ perl -pe 's/.*e=(\S*).*/$1/'

With old perl:

$ perl -ne 'm/e=(\S*)/; print "$1\n"'
2
thkala On

How about this, using just Bash:

$ s="a b c d e=x f g h i"
$ s="${s#*=}"
$ echo "${s%% *}"
x

The used parameter expansions are documented here.

Another one using sed:

$ s="a b c d e=x f g h i"
$ echo "$s" | sed 's|.*=\([^[:space:]]*\).*|\1|'
x

Again with sed:

$ s="a b c d e=x f g h i"
$ echo "$s" | sed 's|.*=||; s|[[:space:]].*||'
x

Another one using cut:

$ s="a b c d e=x f g h i"
$ echo "$s" | cut -d = -f 2 | cut -d ' ' -f 1
x

My personal favourite is the first one: it only needs Bash and it does not launch any additional processes.

EDIT:

As per the comments, here are the expressions above, modified to match e specifically:

$ s="a b c d e=x f g h i"
$ s="${s#*e=}"; echo "${s%% *}"
x
$ s="a b c d e=x f g h i"
$ echo "$s" | sed 's|.*\be=\([^[:space:]]*\).*|\1|'
x
$ echo "$s" | sed 's|.*\be=||; s|[[:space:]].*||'
x
1
Andrew Clark On

Here is a one liner using sed and awk:

$ echo 'a b c d e=x f g h i' | sed 's/=/\n/' | awk '{ getline v; split(v, arr); for (i=1; i<=NF; i++) print $i, "=", arr[i] }'
a = x
b = f
c = g
d = h
e = i

Process is to split into two lines at the = using sed, then loop through the columns in both lines simultaneously using awk

0
Dennis Williamson On

Using Bash >= 3.2 regexes:

string='a b c d e=x f g h i'
pattern=' [^ ]*=([^ ]*) '
[[ $string =~ $pattern ]]
echo ${BASH_REMATCH[1]}