Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep or sed for word containing string

Tags:

regex

grep

sed

example file:

blahblah 123.a.site.com   some-junk
yoyoyoyo 456.a.site.com   more-junk
hihohiho 123.a.site.org   junk-in-the-trunk
lalalala 456.a.site.org   monkey-junk

I want to grep out all those domains in the middle of each line, they all have a common part a.site with which I can grep for, but I can't work out how to do it without returning the whole line?

Maybe sed or a regex is need here as a simple grep isn't enough?

like image 625
jwbensley Avatar asked Nov 09 '11 12:11

jwbensley


People also ask

How do you grep just a word?

The easiest of the two commands is to use grep's -w option. This will find only lines that contain your target word as a complete word. Run the command "grep -w hub" against your target file and you will only see lines that contain the word "hub" as a complete word.

Can we use grep and sed together?

This collection of sed and grep use cases might help you better understand how these commands can be used in Linux. Tools like sed (stream editor) and grep (global regular expression print) are powerful ways to save time and make your work faster.

How do I grep one word in Linux?

To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.

How do I extract text between two words in Unix?

How do I extract text between two words ( <PRE> and </PRE> ) in unix or linux using grep command? Let us see how use the grep command or egrep command to extract data between two words or strings. I also suggest exploring sed/awk/perl commands to extract text between two words on your Linux or Unix machine.


2 Answers

You can do:

grep -o '[^ ]*a\.site[^ ]*' input

or

awk '{print $2}' input

or

sed -e 's/.*\([^ ]*a\.site[^ ]*\).*/\1/g' input
like image 113
codaddict Avatar answered Oct 03 '22 05:10

codaddict


Try this to find anything in that position

  $ sed -r "s/.* ([0-9]*)\.(.*)\.(.*)/\2/g"

 [0-9]* - For match number zero or more time.
 .*     - Match anything zero or more time.
 \.     - Match the exact dot.
 ()     - Which contain the value particular expression in parenthesis, it can be printed using \1,\2..\9. It contain only 1 to 9 buffer space. \0 means it contain all the expressed pattern in the expression.
like image 21
Chandru Avatar answered Oct 03 '22 03:10

Chandru