Search for a specific word in each line and print rest of the line

11,175
sed -n '/search?q=/{s/.*search?q=//;p;}' infile > outfile

Explanation:

/search?q=/ makes the following command set (in curly braces) apply only to lines containing this regex.

s/.*search?q=// substitutes the second part (empty) for the first part.

Then p prints the line.

The -n flag suppresses the default printing of the line.

Actually, you can simplify this like so:

sed -n '/.*search?q=/{s///;p;}' infile > outfile

Because when the pattern fed to the s/ command is left blank, the last used pattern is used again.


EDIT: Thanks to RobertL for pointing out a simplification in the comments:

sed -n 's/.*search?q=//p' infile > outfile

This uses the p flag to the s command, which only prints out the line if a substitution was made.

Share:
11,175

Related videos on Youtube

vsv
Author by

vsv

Updated on September 18, 2022

Comments

  • vsv
    vsv over 1 year

    I have text file with server URL lines like:

    request get https://abc.net/search?q=hello/world/hello/word/search=5&size=10
    request get https://abc.net/search?q=hello/world/hello/world/hello/word=5
    

    In this text file, I want the text after the word "search?q=" string and store in another file output file:

    hello/world/hello/word/search=5&size=10
    hello/world/hello/word/hello/world=5
    hello1world1/hello/world/hello/word
    
    • mikeserv
      mikeserv over 8 years
      cut -d= -f2- <in >out
  • RobertL
    RobertL over 8 years
    How about sed -n 's/.*search?q=//p' ?
  • Wildcard
    Wildcard over 8 years
    Yes, that works too. I usually forget about the flags for the s command. Thanks.