3

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!

1
  • What does "without success" mean? Are you aware of the fact that variables are not expanded in single quotes? Commented Mar 22, 2018 at 14:34

4 Answers 4

1

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 
Sign up to request clarification or add additional context in comments.

Comments

0

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 

Comments

0

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!

Comments

0

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$" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.