0

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 
1
  • cut -d= -f2- <in >out Commented Dec 8, 2015 at 23:53

3 Answers 3

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

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

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

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

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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.