【问题标题】:How do I extract lines out of a text file using bash in linux?如何在 linux 中使用 bash 从文本文件中提取行?
【发布时间】:2013-04-04 01:30:27
【问题描述】:

我想使用 bash 脚本从 linux 中的文本文件中提取 任何包含 MAC 地址 的行,然后在可能的情况下将其保存到另一个文件中?

有使用 sed 和 grep 删除行的不同示例,但到目前为止我还不能让它们为我工作。一般来说,我对编程不是很好,所以它可能比我认为的要容易得多。

下面是我从中提取的文本文件示例。

猫测试.txt

spawn ssh -l user x.x.x.x -p 22 "arp"
DD-WRT Mega
Release xx/xx/xx (SVN revison:xx)
root@x.x.x.x password:
Device1 (x.x.x.x) at xx:xx:xx:xx:xx:xx [ether] on br0
Device2 (x.x.x.x) at xx:xx:xx:xx:xx:xx [ether] on br0
Device3 (x.x.x.x) at xx:xx:xx:xx:xx:xx [ether] on br0

以下是我正在寻找的结果。

结果.txt

Device1 (x.x.x.x) at xx:xx:xx:xx:xx:xx [ether] on br0
Device2 (x.x.x.x) at xx:xx:xx:xx:xx:xx [ether] on br0
Device3 (x.x.x.x) at xx:xx:xx:xx:xx:xx [ether] on br0

如果有人知道如何从一个文件中提取包含 MAC 地址的行并通过 bash 脚本将它们发送到另一个文本文件,那将是一个很大的帮助。

谢谢

【问题讨论】:

    标签: linux bash grep


    【解决方案1】:

    使用grep 可能是最简单的:

    grep -E '(..:){5}..' < infile.txt > outfile.txt
    

    值得注意的是,这在强制匹配方面有点宽松,而不是严格只匹配有效的 mac 地址,但这个表达式也更简单一些,很可能就足够了。

    【讨论】:

      【解决方案2】:

      尝试:

      grep -E "(..:){5}.." file
      

      【讨论】:

        【解决方案3】:

        试试这个:

        grep '([0-9A-F]{2}[:-]){5}([0-9A-F]{2})' < in.txt > out.txt
        

        【讨论】:

          【解决方案4】:

          尝试这样做,这是最可靠,最强大的解决方案=)

          grep -E '\b([[:xdigit:]]{2}:){5}[[:xdigit:]]{2}\b' < file > newfile
          

          【讨论】:

            【解决方案5】:

            对于初学者来说,您可以使用 grep,然后您可以转到 sed,然后您可以学习 awk。看到这是你的第一个问题,发布它肯定比谷歌这个问题更费力:)

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-04-26
              • 1970-01-01
              • 2016-12-14
              • 1970-01-01
              • 1970-01-01
              • 2012-05-12
              相关资源
              最近更新 更多