• Uncategorized

About linux : Get-lines-from-a-file-with-a-specific-pattern-in-Bash

Question Detail

I have this file:

this is line 1 192.168.1.1
this is line 2 192.168.1.2
this is line 3 192.168.1.2
this is line 4 192.168.1.1
this is line 5 192.168.1.2

I would like to get, in a bash script, all lines (with tabs) which contains, for example, the pattern “192.168.1.1”. By this way, I would get:

this is line 1 192.168.1.1
this is line 4 192.168.1.1

But i don’t want this result:

this is line 1 192.168.1.1 this is line 4 192.168.1.1

I tried it with sed without success:

var='192.168.1.1'
body=`sed -n -e '/$var/p' $file`
echo $body

Thanks beforehand!

Question Answer

awk to the rescue!

$ awk -v var='192.168.1.1' '$NF==var' file

this is line 1 192.168.1.1
this is line 4 192.168.1.1

Following sed may help you on same.

var="your_ip"
sed -n "/$var/p"  Input_file

Or in awk following will help on same.

var="your_ip"
awk -v var="$var" 'var==$NF'  Input_file

A simple grep command could do that:

grep 192.168.1.1 filename

Or a more “complex” grep command could do that and write it to another file:

grep 192.168.1.1 filename > new_filename

Hope this helps!

Assuming the data format is well defined like you said:

"this is line <seq> <ip>" 

you could do simply this:

cat file | egrep "192.168.0.1$"

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.