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
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
On
Using Bash >= 3.2 regexes:
string='a b c d e=x f g h i'
pattern=' [^ ]*=([^ ]*) '
[[ $string =~ $pattern ]]
echo ${BASH_REMATCH[1]}
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'
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
How about this, using just Bash:
The used parameter expansions are documented here.
Another one using
sed:Again with
sed:Another one using
cut: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
especifically: