在SO上找不到相关内容。我在终端中运行了以下命令:
>> grep -Rl "curl" ./
这将显示包含关键字curl的文件列表。我想要计算文件数。我能想到的第一种方法是计算终端输出中的行数。如何实现?
使用-l
(行数)开关将结果管道传输到 wc
:
grep -Rl "curl" ./ | wc -l
grep "" -c
,但这个方法更好看 :) - ninhenzo64grep -c
而不是将输出导入到另一个程序中。例如,您甚至不会使用Word以外的文本编辑器更改Word文档中的字符,对吧? - Michael Pgrep -c
不能回答这个问题。 - Dave C将EaterOfCode的评论放在这里作为回答。
grep本身也有-c标志,它只返回计数。
因此,命令和输出可能如下所示。
$ grep -Rl "curl" ./ -c
24
编辑:
尽管这个回答可能更短,看起来比被接受的答案(使用wc
)更好。但我不再同意这一观点。我认为记住可以通过管道输入wc -l
来计算行数要更有用,因为您也可以将其与其他程序一起使用而不仅仅是grep
。
如果最后一行以换行符结尾,使用管道到 'wc' 更好(我知道在这种情况下,它会是这样)
但是,如果最后一行没有以换行符结尾,则 'wc -l' 将返回错误的结果。
例如:
$ echo "asd" | wc -l
将返回1
和
$ echo -n "asd" | wc -l
将返回0
所以我经常使用的是grep <anything> -c
$ echo "asd" | grep "^.*$" -c
1
$ echo -n "asd" | grep "^.*$" -c
1
这比wc -l
返回的结果更接近实际情况。
wc -l
的输出开头有一个制表符会有问题吗? - theonlygusti"abcd4yyyy" | grep 4 -c
统计结果为 1
wc -l
是不够的,因为它没有考虑到换行。# Lines being printed
printf "%s" "$TAIL_BUFFER"
seenlines=0
cols=$( tput cols )
while IFS= read -r line; do
# Remove non-printable characters from the line
lineOfPrintedCharacters=$(echo "$line" | tr -dc '[[:print:]]')
# Get length of the line in characters,
# subtracting the newline:
newLength=$(( $( wc -m <<< "$lineOfPrintedCharacters" ) - 1 ))
# Add at least one line, and one for each time the line length
# exceeds the column size of the terminal
seenlines=$( bc <<< "$seenlines + 1 + ${newLength} / ${cols}" )
# Do not remove lines that finish exactly at the edge of the terminal
if [[ $(( (${newLength}) % ${cols} )) -eq 0 ]] && [[ $newLength -ne 0 ]]; then
seenlines=$((seenlines - 1))
fi
done <<< "$TAIL_BUFFER"
echo "${seenlines} lines seen"
-c
标志,它只返回计数。 - EaterOfCodegrep -Ric "searchpattern" ./
- Karthik Rao