Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use grep to get anything just after `name=`?

Tags:

regex

grep

bash

I’m stuck in trying to grep anything just after name=, include only spaces and alphanumeric.

e.g.:

name=some value here 

I get

some value here 

I’m totally newb in this, the following grep match everything including the name=.

grep 'name=.*' filename 

Any help is much appreciated.

like image 616
ngaame Avatar asked Aug 08 '09 02:08

ngaame


People also ask

What does the '- V option to grep do?

-v means "invert the match" in grep, in other words, return all non matching lines.

How do I use grep to find a phrase?

The easiest of the two commands is to use grep's -w option. This will find only lines that contain your target word as a complete word. Run the command "grep -w hub" against your target file and you will only see lines that contain the word "hub" as a complete word.

Can you use regex with grep?

GNU grep supports three regular expression syntaxes, Basic, Extended, and Perl-compatible. In its simplest form, when no regular expression type is given, grep interpret search patterns as basic regular expressions. To interpret the pattern as an extended regular expression, use the -E ( or --extended-regexp ) option.


2 Answers

As detailed here, you want a positive lookbehind clause, such as:

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

The -P makes grep use the Perl dialect, otherwise you'd probably need to escape the parentheses. You can also, as noted elsewhere, append the -o parameter to print out only what is matched. The part in brackets specifies that you want alphanumerics and spaces.

The advantage of using a positive lookbehind clause is that the "name=" text is not part of the match. If grep highlights matched text, it will only highlight the alphanumeric (and spaces) part. The -o parameter will also not display the "name=" part. And, if you transition this to another program like sed that might capture the text and do something with it, you won't be capturing the "name=" part, although you can also do that by using capturing parenthess.

like image 127
markets Avatar answered Sep 24 '22 17:09

markets


Try this:

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

It tells sed to print nothing (-n) by default, substitute your prefix with nothing, and print if the substitution occurs.

Bonus: if you really need it to only match entries with only spaces and alphanumerics, you can do that too:

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

Here we've added a pattern to match spaces and alphanumerics only until the end of the line ($), and if we match we substitute the group in parentheses and print.

like image 22
John Zwinck Avatar answered Sep 23 '22 17:09

John Zwinck