简体   繁体   English

如何在Linux中使用bash从文本文件中提取行?

[英]How do I extract lines out of a text file using bash in linux?

I would like to extract any line that contains a MAC addresses out of a text file in linux using bash scripting, and then save it into another if this is possible? 我想使用bash脚本从Linux中的文本文件中提取出包含MAC地址的 任何行 ,然后在可能的情况下将其保存到另一行中?

There different examples of using sed, and grep to remove lines, but I have not been able to make them work for me so far. 有使用sed和grep删除行的不同示例,但是到目前为止,我还无法使它们对我有用。 I am not very good with programming in general so it's probably done a lot easier then I think it can be. 我总体上对编程不太好,所以可能比我认为容易得多。

Example of text file below that I am extracting from. 我从中提取以下文本文件的示例。

cat Test.txt 猫Test.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

Below is what I am looking for as a result. 以下是我要寻找的结果。

Result.txt Result.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

If anyone knows how to extract the lines containing the MAC Addresses out of one file and send them to a another text file through a bash script that would be a great help. 如果有人知道如何从一个文件中提取包含MAC地址的行,然后通过bash脚本将它们发送到另一个文本文件,那将是一个很大的帮助。

Thank-you 谢谢

It's probably simplest to use grep : 使用grep可能是最简单的:

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

It's worth noting this is a little relaxed in terms of enforcing matches as opposed to being strict that only a valid mac address is matched, but this expression is also a good bit simpler and will most likely suffice. 值得注意的是,这在强制执行匹配方面有些放松,而不是严格要求仅匹配有效的mac地址,但是此表达式也更简单,并且很可能就足够了。

尝试:

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

尝试这个:

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

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

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

well for starters you can use grep, then you can move onto sed, then you can learn awk. 对于初学者来说,可以使用grep,然后可以转到sed,然后可以学习awk。 Seeing this is your first question, posting it sure took more effort than google the question :) 看到这是您的第一个问题,发布它肯定比Google花费更多的努力:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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