我如何只获取grep中的数字?
我有这样的文件:
other lines . . . blah blah blah (:34)
我希望在上面的文件中找到数字的出现。 我提出了:
grep [0-9] filename
但这就是印刷整体:
blah blah blah (:34)
相反,我只想要34
。 有没有办法这样做?
您可以使用grep -E
访问扩展的正则表达式语法(与egrep相同)
我创建了一个包含以下内容的测试文件:
>cat testfile this is some text with some random lines again some text ok now going for numbers (:32) ok now going for numbers (:12) ok now going for numbers (:132) ok now going for numbers (:1324)
现在单独从您可以使用的文本中查找数字
>grep -Eo '[0-9]{1,4}' testfile 32 12 132 1324
将输出。
这里“-o”仅用于输出行的匹配段,而不是行的全部内容。
波浪形括号(例如{和})表示匹配的实例数。 {1,4}要求前一个字符或字符类必须至少出现一次,但不得超过四次。
希望这可以帮助
您可以使用POSIX标准 9.3.5节中指定的RE括号表达式[:digit:]
,与-o
标志组合使用,仅打印匹配的“单词”
$ grep -o '[[:digit:]]*' <<< $'No number in this line\nbut 123 here' 123
grep -o
将仅打印该行的匹配部分。 否则grep会打印带有图案的任何线条。
我会使用curl本地或远程访问你的文件,然后我会用(:)中包含的数字grep行,然后关闭这些文件并写入文件
接受的答案忽略了文件的前一行中可能有数字,它确实适用于示例数据,但如果文件是远程的呢?
本地
curl file:///home/$USER/Public/input.txt | grep -o '(:.*)' | cut -d ":" -f 2 | cut -d ")" -f 1 > output.txt
在此示例中,将覆盖当前文件夹中的output.txt
,我们将从您的Public文件夹中访问input.txt
。
远程
curl https://yoursite.com/Public/input.txt | grep -o '(:.*)' | cut -d ":" -f 2 | cut -d ")" -f 1 > output.txt
在此示例中,将覆盖当前文件夹中的output.txt
,我们将从https://yoursite.com/Public/
访问input.txt
。