【问题标题】:Get lines from a file with a specific pattern in Bash在 Bash 中从具有特定模式的文件中获取行
【发布时间】:2018-03-22 14:27:00
【问题描述】:

我有这个文件:

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

先谢谢了!

【问题讨论】:

  • “没有成功”是什么意思?你知道变量不是用单引号展开的吗?

标签: linux bash shell file


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    关注sed 可能对您有所帮助。

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

    或者在awk 关注同样会有所帮助。

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

    【讨论】:

      【解决方案3】:

      一个简单的grep 命令就可以做到这一点:

      grep 192.168.1.1 filename
      

      或者更“复杂”的grep 命令可以做到这一点并将其写入另一个文件:

      grep 192.168.1.1 filename > new_filename
      

      希望这会有所帮助!

      【讨论】:

        【解决方案4】:

        假设数据格式像你说的那样定义明确:

        "this is line <seq> <ip>" 
        

        你可以这样做:

        cat file | egrep "192.168.0.1$"
        

        【讨论】:

          猜你喜欢
          • 2016-08-03
          • 2020-11-07
          • 2013-06-25
          • 1970-01-01
          • 2013-06-20
          • 1970-01-01
          • 2016-07-18
          • 1970-01-01
          • 2013-06-26
          相关资源
          最近更新 更多