6

i want to extract a word from a sentence in bash script .it uses both coma and space as separators.

ex:- date=crossed 122 name=foo , userid=234567 , sessionid=2233445axdfg5209  associd=2

I have above sentence in which the interesting part is name=foo .the key name is always same but the string foo may vary. also other parameters may or may not be there .

i need to extract above key value pair. so output would be :

name=foo

what is the best way to do it in shell script?

thanks!

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
jch
  • 1,155
  • 3
  • 14
  • 27

3 Answers3

8

grep is useful here:

grep -o 'name=[^ ,]\+'
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
3

If you know that the value after name will never contain spaces or quotes, and there are no other complications, you could do this with a sed one-liner:

sed -e 's/^.*\(name=[^ ,]*\).*$/\1/'

That just says to replace the entire line with the part that matches name= followed by any number of non-comma, non-space characters.

This not going to be terribly robust if there are possibilities like name="quoted string" or name=string\ with\ escaped\ spaces. But it will work for the limited case.

If you want to store the result in a shell variable you might do something like (in bash)

pair=$(echo $input | sed -e 's/^.*\(name=[^ ,]*\).*$/\1/')
echo $pair

which prints name=foo, as intended.

Tested with GNU sed 4.2.1 and Bash 4.2.10

  • Updated to say you can do exactly the same thing more elegantly by replacing the `sed` command above with `egrep -e 'name=[^ ,]*' -o`, where the `-o` means to only print out the matching portion of the line. –  Nov 01 '11 at 23:43
  • tried both on on SuSE11 , not sure what is the bash version..the first one doesnt show the output , the second one keeps running and dont exit. – jch Nov 03 '11 at 18:08
  • See Glenn's comment on his answer (which is simpler and better than mine anyway). Where is your input coming from -- a file, stored in a shell variable, or something else? –  Nov 03 '11 at 21:45
2

If "name=foo" is always in the same position in the line you could simply use: awk '{print($3)}', that will extract the third word in your line which is name=foo in your case.

Debugger
  • 9,130
  • 17
  • 45
  • 53