How to use grep to get something only after `name =`?

I was stuck in trying to grep something right after name= , including only spaces and alphanumeric characters.

eg:.

 name=some value here 

I get

 some value here 

Im completely newb in this, the following grep matches everything, including name= .

 grep 'name=.*' filename 

Any help is greatly appreciated.

+44
bash regex grep
Aug 08 '09 at 2:45
source share
5 answers

As a detailed here, you want to create a positive lookbehind condition, for example:

 grep -P '(?<=name=)[ A-Za-z0-9]*' filename 

-P makes grep use the Perl dialect, otherwise you will probably need to avoid parentheses. You can also mark, as indicated elsewhere, add the -o option to print only what matches. The part in parentheses indicates that you want alphanumeric characters and spaces.

The advantage of using the positive lookbehind clause is that the text name = is not part of the match. If grep selects consistent text, it will only select the alphanumeric (and spatial) part. The -o option also does not display the "name =" part. And if you switch to another program, for example sed, which can capture text and do something with it, you will not capture the "name =" part, although you can also do this using the parent mines capture.

+71
Aug 08 '09 at 2:52
source share
— -

Try the following:

 sed -n 's/^name=//p' filename 

It tells sed to not print anything (-n) by default, nothing replaces your prefix, and print if a substitution occurs.

Bonus: if you really need it to match only spaces and alphanumeric characters, you can also do this:

 sed -n 's/^name=\([ 0-9a-zA-Z]*$\)/\1/p' filename 

Here we added a pattern to match spaces and alphanumeric characters only to the end of the line ($), and if we match, we will replace the group in parentheses and print.

+21
Aug 08 '09 at 2:55
source share

grep is not retrieved as you expect. You need

 grep "name=" file.txt | cut -d'=' -f1- 
+4
Aug 08 '09 at 2:50
source share

Gawk

 echo "name=some value here" | awk -F"=" '/name=/ { print $2}' 

or bash

 str="name=some value here" IFS="=" set -- $str echo $1 unset IFS 

or

 str="name=some value here" str=${str/name=/} 
+3
Aug 08 '09 at 4:50
source share

grep will print the entire line where it matches the pattern. To print only the template, use the grep -o option. You probably also need to use sed to remove part of the name = template.

 grep -o 'name=[0-9a-zA-Z ]' myfile | sed /^name=/d 
+1
Aug 08 '09 at 2:48
source share



All Articles