I'm having a problem to grep specific keyword and its content. This is sample file, the actual file is larger than this.


user@linux:~$ cat url.txt 
abcrandomtextdef another random text blablabla
another random iwantthis text abcrandomtextdef url=https://www.google.com ghirandomtextjkl
ghirandomtextjkl another random text yadayada
wxyz iwantthis abcdef url=yahoo.com yaday

Desired output would be like this.

iwantthis url=https://www.google.com
iwantthis url=yahoo.com

These are my attempts to get that output, but as you can see it didn't really work.

user@linux:~$ grep url= url.txt | cut -d ' ' -f3,6
iwantthis url=https://www.google.com

1 Answer 1


sed would seem to be the right task for this:

% sed -n 's/.* \(iwantthis\) .* \(url=[^ ]*\) .*/\1 \2/p' url.txt
iwantthis url=https://www.google.com
iwantthis url=yahoo.com

How this works:

-n -- only print lines that match with a "p" command

s/.../p -- search and replace, printing lines that match

.* \(iwantthis\) .* \(url=[^ ]*\) .* -- This will look for the word "iwantthis" surrounded by spaces and remember it, and also look for "url=" followed by non-spaces, and rememeber that. The .* at each end mean that stuff before "iwantthis" and stuff after the URL are discarded.

/\1 \2 -- Replace it with the two remembered words

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.