我有一个多行字符串,如下所示
"this is a sample
this is a second sample
same length the 1 above
this is a third sample"
有什么方法可以找到哪些行具有最大长度(以字符数计)以及长度是多少。在上面的示例中,这将是第二行和第三行。
答案1
string="this is a sample
this is a second sample
same length the 1 above
this is a third sample"
printf '%s\n' "$string" | awk -v max=-1 '
{l = length}
l > max {max = l; output = "Max length: " max RS}
l == max {output = output NR ": " $0 RS}
END {if (max >= 0) printf "%s", output}'
输出:
Max length: 23
2: this is a second sample
3: same length the 1 above
答案2
echo "this is a sample
this is a second sample
this is a third sample" | \
while read line; do
echo ${#line} $line
done | sort -n
为您提供具有长度的行列表,按长度排序
答案3
总统计数据顶部使用 GNU 的最长行awk解决方案:
awk 'BEGIN{ PROCINFO["sorted_in"]="@ind_num_desc" }
{ len=length; a[len]=(a[len])? a[len]", "NR:NR }
END{ for(i in a) printf "Length: %s, row number(s): %s\n",i,a[i] }' file
输出:
Length: 23, row number(s): 2, 3
Length: 22, row number(s): 4
Length: 16, row number(s): 1