使用重击,我想显示任意文本中至少包含一个数字(数字仅由一位或几位数字组成)的行数。
我还想将检测到的数字显示为一行。提供了文本文件 example.txt 的示例以及所需的输出。
$ cat example.txt
Electronic mail is a method of exchanging digital messages between computer
users; such messaging first entered substantial
use in the 1960s and by the 1970s had taken the form now recognised as email.
These are spams email ids:
08av , 29809, pankajdhaka.dav, 165 .
23673 ; meetshrotriya; 221965; 1592yahoo.in
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
These are incorrect:
065
kartikkumar781r2#
1975, 123
期望的输出:
Number of lines having one or more digits are: 4
Digits found:
29809
165
23673
221965
065
1975
123
答案1
尝试:
printf '
Number of lines having one or more digits are: %d
Digits found:
%s
' "$(grep -Ecw '[[:digit:]]+' infile)" "$(grep -Eow '[[:digit:]]+' infile)"
答案2
这个答案是基于您提供的示例。
这意味着如果数字散布在文件中的example.txt
分隔符与任一不同space
,,
则;
脚本可能会给出不完整的结果。无论如何,我将此解决方案推广到允许空格、逗号和分号任意组合的分隔模式。如果您需要,添加不同的分隔符很简单。
$ cat my_script.bash
#!/usr/bin/env bash
printf "Number of lines having one or more digits is: %s\n" \
"$(grep -cE '(^| )[0-9]+( |,|;|$)' $1)"
printf "Digits found:\n"
printf "%s\n" "$(sed -E 's/ |\,|\;//g;' < <(grep -o -E '(^|( *|,|;)+)[0-9]+( |,|;|$)' $1))"
我确信完全可以使用sed
,但grep
在这种情况下太诱人了。
要使用,请使文件my_script.bash
可执行并运行:
$ chmod ug+x my_script.bash
$ my_script.bash example.txt
Number of lines having one or more digits are: 4
Digits found:
29809
165
23673
221965
065
1975
123
答案3
怎么样(GNU grep,因为 和\<
)\>
:
$ grep -o '\<[0-9][0-9]*\>' example.txt
29809
165
23673
221965
065
1975
123
答案4
和perl
:
perl -lne '
if (@n = /\b\d+\b/g) {push @all, @n; $n++}
END {print for "$n line(s) with numbers. Number(s):", @all}
' your-file
+
这是 1 个或多个 ( ) ASCII十进制数字的序列d
,前面和后面是词b
边界或 IOW 之前或之后都没有 ASCII 单词字符 ( a-zA-Z0-9_
)。