简体   繁体   English

使用Sed或Awk根据行是否包含数值将文件分为两个

[英]Using Sed or Awk to divide a file into two based on whether a line contains a numeric value

I have used sed and awk for little while now, but I am having a challenge with the below problem. 我已经使用sed和awk了很短一段时间,但是我遇到了以下问题的挑战。 I am asking for an experienced sed/awk guru to help. 我要求有经验的sed / awk专家来提供帮助。

I have a file where some lines have numbers and some lines do not, like: 我有一个文件,其中有些行有数字,有些行没有数字,例如:

afjjdjfj.uihuihi
trfg.rtyhd
0rtgfd.tjbghhh
hbvfd4.rtgbvdgf
00fhfg.fdrgf
rtygfd.ijhniuh

etc. 等等

I would like to have exactly two files out of this one, where every line is represented in one of the two files (none are deleted). 我想从这个文件中准确地得到两个文件,其中每一行都用两个文件之一表示(没有删除)。

One containing all lines with any numbers 0-9 on them so given above file result would be: 其中包含所有数字为0-9的所有行的一个,因此在文件结果上方给出的结果是:

0rtgfd.tjbghhh
hbvfd4.rtgbvdgf
00fhfg.fdrgf

and another file containing the rest of the lines that do not have any numbers 0-9 on them, so given the above, file it would be: 还有另一个文件,其中包含其余行,这些行上没有任何数字0-9,因此在上述情况下,文件应为:

afjjdjfj.uihuihi
trfg.rtyhd
rtygfd.ijhniuh

I've tried different strategies in both sed and awk and nothing is giving me exactly what I need. 我在sed和awk中都尝试了不同的策略,但是没有任何东西可以满足我的需求。

What would be the best sed or awk one liner to solve this problem? 解决此问题的最佳sed或awk one衬垫是什么?

Thank you for your time, 感谢您的时间,

Tom 汤姆

轻松使用Awk:

awk '/[0-9]/{print > file1; next} {print > file2}' inputfile

With single GNU sed command: 使用单个GNU sed命令:

sed -ne '/[0-9]/w with_digits.txt' -e '//!w no_digits.txt' input

Results: 结果:

> cat no_digits.txt 
afjjdjfj.uihuihi
trfg.rtyhd
rtygfd.ijhniuh

> cat with_digits.txt
0rtgfd.tjbghhh
hbvfd4.rtgbvdgf
00fhfg.fdrgf

w filename w文件名
Write the pattern space to filename. 将模式空间写入文件名。

If you don't mind running twice over the input, you can use just grep: 如果您不介意对输入运行两次,则可以仅使用grep:

grep    '[0-9]' input > with_digits
grep -v '[0-9]' input > without_digits
perl -MFile::Slurp -lpe '/\d/ ? append_file("digits.txt",$_) : append_file("no_digits.txt",$_)' input.txt

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

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