Rahul
Rahul

Reputation: 418

get only string after matching pattern and exclude everything else

I would like to get string which comes after matching pattern and exclude everything else. For example say,

Nov 17 21:52:06 web01-san roundcube: <he1v330n> User dxxssjksdfd [121.177.26.200]; \
Message for undisclosed-recipients:, [email protected]
Nov 17 21:48:26 web01-san roundcube: <fqu8k29l> User cxcnjdfdssd [121.177.26.200]; \
Message for undisclosed-recipients:, [email protected]

So I would like to get ONLY string after pattern User and exclude everything else, so output should be

User dxxssjksdfd
User cxcnjdfdssd

I've tried grep -Po 'User\K[^\s]*' but it doesn't give what I want. How can I do that ?

Upvotes: 3

Views: 13420

Answers (2)

Akshay Hegde
Akshay Hegde

Reputation: 16997

$ cat infile
Nov 17 21:52:06 web01-san roundcube: <he1v330n> User dxxssjksdfd [121.177.26.200]; \
Message for undisclosed-recipients:, [email protected]
Nov 17 21:48:26 web01-san roundcube: <fqu8k29l> User cxcnjdfdssd [121.177.26.200]; \
Message for undisclosed-recipients:, [email protected]

Using grep

$ grep -Po 'User [^\s]*'  infile
User dxxssjksdfd 
User cxcnjdfdssd 

Using awk

$ awk  'match($0,/User [^ ]*/){ print substr($0, RSTART,RLENGTH)}'  infile
User dxxssjksdfd
User cxcnjdfdssd

Using GNU awk

$ awk  'match($0,/User [^ ]*/,arr){ print arr[0]}'  infile
User dxxssjksdfd
User cxcnjdfdssd

Explanation:

/User [^\s]*/

  • User matches the characters User literally (case sensitive)
  • Match a single character not present in the list below [^\s]*
  • * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  • \s matches any whitespace character (equal to [\r\n\t\f\v ])

Upvotes: 5

RavinderSingh13
RavinderSingh13

Reputation: 133750

Solution 1st: Following awk should be helping you in same.

awk -v RS=" " '/User/{getline;print "User",$0}'   Input_file

Output will be as follows.

User dxxssjksdfd
User cxcnjdfdssd

Solution 2nd: You could use following too by going through the fields of line too.

awk '{for(i=1;i<=NF;i++){if($i ~ /User/){print $i,$(i+1)}}}'   Input_file

Solution 3rd: By using sub utility of awk here too.

awk 'sub(/.*User/,""){print "User",$1}'   Input_file

Upvotes: 4

Related Questions