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.
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.
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
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
Will
grepdo? Assuming I understand your question correctly:where
s='a b c d e=x f g h i'