Perl 查找最长的子列表
我有一个包含列表和子列表的文件,我想使用命令行工具提取最长的子列表 文件示例:Perl 查找最长的子列表,perl,shell,awk,grep,wc,Perl,Shell,Awk,Grep,Wc,我有一个包含列表和子列表的文件,我想使用命令行工具提取最长的子列表 文件示例: * Item1 ** SubItem1 ** ... ** SubItemN * Item2 ** SubItem1 ** ... ** SubItemN * ... ** ... * ItemN ** SubItem1 ** ... ** SubItemN 我试图知道这是否可以轻松完成,否则我将编写一个Perl脚本 cat file.txt | grep -nE "^\*[^\*].*" | cut -d
* Item1
** SubItem1
** ...
** SubItemN
* Item2
** SubItem1
** ...
** SubItemN
* ...
** ...
* ItemN
** SubItem1
** ...
** SubItemN
我试图知道这是否可以轻松完成,否则我将编写一个Perl脚本
cat file.txt | grep -nE "^\*[^\*].*" | cut -d ":" -f 1,1 | tee tmp | awk 'NR==1{s=$1;next} {print $1-s;s=$1}' > tmp2
echo 0 >> tmp2
res=`paste tmp tmp2 | sort -nrk 2,2 | head -n 1`
line=`echo "$res" | cut -f 1,1`
ln=`echo "$res" | cut -f 2,2`
cat file.txt | tail -n +$line | head -n $ln
rm tmp tmp2
肯定有一个较短的解决方案:)
肯定有一个较短的解决方案:)
通过使用tac
反转文件并使用awk
显示每个子列表的长度:
$ tac file | awk '/^\*\*/{c++}/^\*[^*]/{print c,$2;c=0}'
5 numbers
3 colors
6 letters
仅打印最大子列表的长度:
$ tac file | awk '/^\*\*/{c++}/^\*[^*]/{if(c>m){m=c;l=$2}c=0}END{print m,l}'
6 letters
通过使用tac
反转文件并使用awk
显示每个子列表的长度:
$ tac file | awk '/^\*\*/{c++}/^\*[^*]/{print c,$2;c=0}'
5 numbers
3 colors
6 letters
仅打印最大子列表的长度:
$ tac file | awk '/^\*\*/{c++}/^\*[^*]/{if(c>m){m=c;l=$2}c=0}END{print m,l}'
6 letters
Perl一行程序:
perl -00 -ne '$n=tr/\n/\n/; if ($n>$m) {$m=$n; $max=$_}; END {print $max}' file
仅使用bash:
max=0
while read bullet thingy; do
case $bullet in
"*") item=$thingy; count=0 ;;
"**") ((count++)) ;;
"") (( count > max )) && { max_item=$item; max=$count; } ;;
esac
done < <(cat file; echo)
echo $max_item $max
Perl一行程序:
perl -00 -ne '$n=tr/\n/\n/; if ($n>$m) {$m=$n; $max=$_}; END {print $max}' file
仅使用bash:
max=0
while read bullet thingy; do
case $bullet in
"*") item=$thingy; count=0 ;;
"**") ((count++)) ;;
"") (( count > max )) && { max_item=$item; max=$count; } ;;
esac
done < <(cat file; echo)
echo $max_item $max
比Perl脚本简单?我不这么认为。听起来像是2-3行Perl。比Perl脚本简单吗?我不这么认为。听起来像大约2-3行Perl.awk:line 1:正则表达式编译失败(语法错误^*或^+^*[^*]awk:line 1:正则表达式编译失败(语法错误^*或^+^*[^*]它一次读取一个段落()--将每个段落存储在特殊变量中。它统计段落()中的换行数。剩下的,找到最大值,应该是很明显的。@JohnJohnGa,我在我的评论中添加了一些链接以供进一步启发。它一次读取一个段落()——将每个段落存储在特殊变量中。它统计段落()中的换行数。剩下的,找到最大值,应该是很明显的。@JohnJohnGa,我在我的评论中添加了一些链接以供进一步启发