0

I have a text:

This is my=test and class=76

This is my=test and class=78

This is my=test2 and class=76

This is my=test3 and class=75

This is my=test1 and class=79.

I want to grep all the word starting with "class=" with the values without printing the whole line the output should be:

class=76
class=78
class=76
class=75
class=79

any command that can help me on this?

I tried this :

grep -E '(^|\s+)class=(?=\s|$)' file

but was not getting any output.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
A. Gupta
  • 77
  • 2
  • 9
  • 1
    Possible duplicate of [Can grep show only words that match search pattern?](https://stackoverflow.com/questions/1546711/can-grep-show-only-words-that-match-search-pattern) – tripleee Nov 22 '18 at 08:39
  • Possible duplicate of https://stackoverflow.com/questions/45965192/why-s-do-not-match-the-space-in-macro-with-grep – tripleee Nov 22 '18 at 08:39

2 Answers2

5

Your (^|\s+)class=(?=\s|$) pattern is not POSIX compliant because it contains a positive lookahead (?=\s|$) that is meant to match a location that is followed with a whitespace or end of string position. As you want to match digits right after class=, this lookahead makes no sense even in a PCRE regex. The (^|\s+) group is meant to match start of string or 1 or more whitespaces, but it seems a mere word boundary will do here.

You may use

grep -oE '\<class=[^ ]+' file

See the online demo

Details

  • o - enables the output mode, only outputs matches
  • E - enables POSIX ERE syntax
  • \< - a word boundary (also \b can be used instead)
  • class= - a literal string
  • [^ ]+ - 1 or more chars other than space

Equivalent BRE POSIX version:

grep -o '\<class=[^ ]*' file

Tested with grep (GNU grep) 2.27.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

Using Perl-oneliner

> data="This is my=test and class=76 This is my=test and class=78 This is my=test2 and \n class=76 This is my=test3 and class=75 This is my=test1 and class=79."
> perl -0777 -ne ' { while(/(class=(\d+))/g) { print "$1\n" } } ' <<< "$data"                                                                                   
class=76
class=78
class=76
class=75
class=79
> 

Works, even if you have the data in a file

> echo "$data" > gupta.txt
> perl -0777 -ne ' { while(/(class=(\d+))/g) { print "$1\n" } } ' gupta.txt 
class=76
class=78
class=76
class=75
class=79
> 
stack0114106
  • 8,534
  • 3
  • 13
  • 38