简体   繁体   中英

Get lines from a file with a specific pattern in Bash

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM