简体   繁体   中英

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

I have a file tmpFile containing:

wqf____32qwfe
123412
qqwef123414
12039421
...

In tmpFile there are lines with only numbers in them, or lines that can contain any kind of characters.

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?

To print lines that only contain digits with GNU grep is:

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

or with any 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 ).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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