我有一个文本文件,我想扫描这个文本文件中的特定数字。假设文本文件是:
asdg32dasdgdsa
dsagdssa11
adad 12345
dsaga
Run Code Online (Sandbox Code Playgroud)
现在我想搜索一个长度为 5 的数字并将其打印出来 ( 12345
)。
我怎样才能在 Linux 中做到这一点?
您正在寻找以下grep
命令:
DESCRIPTION
grep searches the named input FILEs for lines containing a match to the
given PATTERN. If no files are specified, or if the file “-” is given,
grep searches standard input. By default, grep prints the matching
lines.
Run Code Online (Sandbox Code Playgroud)
因此,要找到 number 12345
,请运行:
$ grep 12345 file
adad 12345
Run Code Online (Sandbox Code Playgroud)
这将打印所有匹配的行12345
。要仅打印该行的匹配部分,请使用以下-o
标志:
$ grep -o 12345 file
12345
Run Code Online (Sandbox Code Playgroud)
要查找长度为 5 的任何连续数字段,您可以使用以下方法之一:
$ grep -o '[0-9][0-9][0-9][0-9][0-9]' file
12345
$ grep -o '[0-9]\{5\}' file
12345
$ grep -Eo '[0-9]{5}' file
12345
$ grep -Po '\d{5}' file
12345
Run Code Online (Sandbox Code Playgroud)
要执行相同的操作但忽略任何超过 5 位的数字,请使用:
$ grep -Po '[^\d]\K[0-9]{5}[^\d]*' file
12345
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9355 次 |
最近记录: |