[英]Get lines from a file with a specific pattern in Bash
我有這個文件:
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
我想在bash腳本中獲得所有行(帶有制表符),其中包含例如模式“192.168.1.1”。 通過這種方式,我會得到:
this is line 1 192.168.1.1
this is line 4 192.168.1.1
但我不想要這個結果:
this is line 1 192.168.1.1 this is line 4 192.168.1.1
我用sed試了一下但沒有成功:
var='192.168.1.1'
body=`sed -n -e '/$var/p' $file`
echo $body
先謝謝!
awk
來救援!
$ 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
以下sed
可能會幫助你。
var="your_ip"
sed -n "/$var/p" Input_file
或者在awk
關注同樣的幫助。
var="your_ip"
awk -v var="$var" 'var==$NF' Input_file
一個簡單的grep
命令可以做到這一點:
grep 192.168.1.1 filename
或者更復雜的grep
命令可以執行此操作並將其寫入另一個文件:
grep 192.168.1.1 filename > new_filename
希望這可以幫助!
假設數據格式很好地定義,就像你說的那樣:
"this is line <seq> <ip>"
你可以做到這一點:
cat file | egrep "192.168.0.1$"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.