Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get extract a word from a line in bash shell script [duplicate]

Tags:

bash

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!

like image 699
jch Avatar asked Nov 01 '11 19:11

jch


People also ask

How do you slice a string in bash?

Using the cut Command Specifying the character index isn't the only way to extract a substring. You can also use the -d and -f flags to extract a string by specifying characters to split on. The -d flag lets you specify the delimiter to split on while -f lets you choose which substring of the split to choose.

What is $@ in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

grep is useful here:

grep -o 'name=[^ ,]\+'
like image 122
glenn jackman Avatar answered Sep 19 '22 06:09

glenn jackman