简体   繁体   English

删除与sed模式不匹配的所有行

[英]deleting all lines that don't match a pattern with sed

I have a file tmpFile containing: 我有一个文件tmpFile包含:

wqf____32qwfe
123412
qqwef123414
12039421
...

In tmpFile there are lines with only numbers in them, or lines that can contain any kind of characters. tmpFile中,行中仅包含数字,或者行中可以包含任何类型的字符。

I would like to keep lines that contain only integer numbers. 我想保留仅包含整数的行。 How can I achieve this? 我该如何实现?

Though you CAN use sed for this, the job is to G lobally search for a R egular E xpression and P rint the result so guess what tool was invented to do precisely this job? 虽然你可以为此使用SED的工作是与G lobally搜索A R egularé上的表达和P RINT结果如此猜测的发明是为了做正是这个工作什么工具?

To print lines that only contain digits with GNU grep is: 要使用GNU grep打印仅包含数字的行,请执行以下操作:

grep -E '^[0-9]+$' file

or with any grep: 或任何grep:

grep '^[0-9][0-9]*$' file

To print lines that contain non-digits: 要打印包含非数字的行:

grep '[^0-9]' file

To print lines that do not contain digits (includes empty lines): 要打印不包含数字的行(包括空行):

grep -v '[0-9]' file

To print lines that do not contain non-digits (includes empty lines): 要打印不包含数字的行(包括空行):

grep -v '[^0-9]' file
sed '/^[0-9]\+$/!d' tmpFile

The ! ! inverts the logic. 颠倒逻辑。 Note that \\+ is not part of the base functionality of POSIX-compliant versions of sed (eg BSD or Mac OS X sed ). 请注意, \\+不是POSIX兼容版本sed (例如BSD或Mac OS X sed )的基本功能的一部分。

sed '/^[0-9]\{1,\}$/!d' tmpFile

This would work, looking for one or more digits. 查找一个或多个数字将起作用。

There are other ways of achieving the same overall effect, too, especially in this limited context. 还有其他方法可以达到相同的总体效果,尤其是在这种有限的情况下。 If you need to do this as part of a bigger script, this is the direct answer to your requirement. 如果您需要在更大的脚本中执行此操作,则这是对您的要求的直接答案。

You can suppress printing pattern space and only print the lines that match a numeric pattern, eg: 您可以取消打印图案空间,仅打印与数字图案匹配的行,例如:

$ sed -n '/^[0-9]\+$/p' file
123412
12039421

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

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