1

Just a stupid question. Provide a code snippet

b="a=2"

How to extract the value 2 and assign it to variable a

爱国者
  • 4,298
  • 9
  • 47
  • 66

6 Answers6

3

You could just eval the code..

eval $b
Geoffrey
  • 10,843
  • 3
  • 33
  • 46
  • 1
    Until somebody does `b="rm -rf /;a=2"`. As the saying goes *if eval is the answer, you're asking the wrong question* – SiegeX Jan 11 '12 at 07:39
  • @SergeX - Very true, but not an issue if its not a field that a an argument is used in (trusted). – Geoffrey Jan 11 '12 at 07:41
3

I am renowned to give ugly solutions so I won't dissapoint you -

[jaypal:~/Temp] a=$(awk '{print $(NF-1)}' FS='["=]' <<< 'b="a=2"')
[jaypal:~/Temp] echo $a
2

Less intense solution

[jaypal:~/Temp] a=$(awk -F= '{print $NF}' <<< $b)
[jaypal:~/Temp] echo $a
2
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
  • 1
    You might get your P.R. person to rebrand your work as *intense and portable* rather than *ugly*. :-) – wallyk Jan 11 '12 at 07:42
  • +1 for an *intense and portable* answer ;) Although you could make it slightly less intense if you use single quotes for `FS` so you don't have to escape the double-quote and set `FS` at the end so you don't need `-v` `a=$(awk '{print $(NF-1)}' FS='["=]' <<< 'b="a=2"';)` – SiegeX Jan 11 '12 at 08:03
  • Thanks @SiegeX .. have updated the answer... There is a `less intense` solution too for the faint hearted. I am on a run with 20 solutions getting 28 up-votes with **no accepted** answer. I wonder why? :) – jaypal singh Jan 11 '12 at 08:08
2
a=${b#a=}

Take the value of $b, remove the leading text a=; assign what's left (2) to a.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
2
$ b="a=2"
$ var=${b##*=}; echo $var
2
SiegeX
  • 135,741
  • 24
  • 144
  • 154
1

If you are looking for a shell utility to do something like that, you can use the cut command.

To take your example, try:

echo "abcdefg" | cut -c3-5

Where -cN-M tells the cut command to return columns N to M, inclusive.

REF: What linux shell command returns a part of a string? and Extract substring in Bash

Community
  • 1
  • 1
Manish Shrivastava
  • 30,617
  • 13
  • 97
  • 101
  • Using `cut` is a heavy-duty way to do it given that the shell has built-in functionality that can do it. With `bash` and still using `cut`, you could save on a pipe using `a=$(cut -c3 <<< $b)`. For other ways to do it, see the other answers. – Jonathan Leffler Jan 11 '12 at 07:28
  • you can also check this.. I googled http://ask.metafilter.com/80862/how-split-a-string-in-bash – Manish Shrivastava Jan 11 '12 at 07:29
1

another portable solution

IFS='='
set -- $b
let "$1=$2"
glenn jackman
  • 238,783
  • 38
  • 220
  • 352