Answers:
与grep
:
grep -En '.{12}' file
对于至少12个字符长的行。
有几个文件:
find . -type f -exec grep -En '.{12}' {} +
一些grep
实现(例如GNU grep
)可以自己进行文件查找。
grep -rEn '.{12}' .
但要注意符号链接和其他非常规文件。
AWK解决方案
awk '{
if (length($0) > 5)
print $0;'} yourfile
或者,更简洁地说:
awk 'length > 5' file
awk 'length > 5'
awk
,它会awk '/^.{6,}/'
awk '/.{6}/'
(实际上,直到最近,GNU awk一直是这样,除非您将POSIXLY_CORRECT传递给它的环境,否则它将无法工作)。
重击解决方案
#!/bin/bash
count=0
while read; do
((++count))
len=${#REPLY}
if ((len > 80)); then
echo "Line $count is $len characters."
fi
done
因此,例如./whatever.sh < input.file
。这不包括通过从中减去1来换行$len
;如果不希望这样,或者您的输入使用CRLF结尾,则应进行相应调整。
${#line}
避开expr
叉子?
bash
溶液。但是请注意,除非您坚持在IFS=
前面,否则read
前导空格将被忽略。
$line
因此无需减去一。
read
指定要读取的名称,它将读取REPLY
并包含所有空格。无需IFS
设置。
while read
处理文本的循环确实是不好的做法。
使用perl
(例如),假设您要搜索长度超过80个字符的行:
显示行:
$ perl -nle 'print if length > 80' your_file
要显示行号:
$ perl -nle 'print "$.\n" if length > 80' your_file
或两者:
$ perl -nle 'print "[$.]: $_\n" if length > 80' your_file
-l
命令行,perl
以计算行中的换行符。
红宝石:
ruby -lne 'puts $_ if $_.size > 5' intputfile
Python:
python -c "import sys;[ sys.stdout.write(''.join(line)) for line in sys.stdin if len(line.strip()) > 5 ]" < inputfile
这是另一个bash解决方案(bash 4):
minlen=5 # minimum length of a line
mapfile -tO1 < inputfile # Map the file to the array MAPFILE (by default)
# Start the array at index 1
for i in "${!MAPFILE[@]}"; do
(( ${#MAPFILE[i]} > minlen )) || unset MAPFILE[i] # Remove shorter elements
done
结果数组很稀疏,因此可以维护数组索引。自从1开始,索引就是我们保留的行的行号。我们只能输出那些行号:
printf 'Long lines found at: '
printf '%d, ' "${!MAPFILE[@]}"
echo
或者我们可以自己输出行:
printf '%s\n' "${MAPFILE[@]}"
grep
),行号或其他内容(也许您想对它们执行其他操作)?可能最方便的方法取决于下一步如何处理这些行。