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:

  • cut -d= -f2- <in >out – mikeserv Dec 8 '15 at 23:53
sed -n '/search?q=/{s/.*search?q=//;p;}' infile > outfile


/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.

  • 1
    How about sed -n 's/.*search?q=//p' ? – RobertL Dec 9 '15 at 0:55
  • Yes, that works too. I usually forget about the flags for the s command. Thanks. – Wildcard Dec 9 '15 at 1:22

If your version of grep supports PCRE, you could use something like

grep -oP 'search\?q=\K.*' infile > outfile

with perl based regex search using lookbehind we can get your required result.

grep -oP '(?<=search\?q\=)[^ ]*' *filename*

remember to add \ before ? and = as those are part of lookbehind regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.