Linux 如果列中出现不同的数字,请插入新行
我有一个专栏Linux 如果列中出现不同的数字,请插入新行,linux,bash,Linux,Bash,我有一个专栏 1 1 1 2 2 2 当列中的值更改时,我想插入一个空行: 1 1 1 <- blank line 2 2 2 1 1. 1. 读L时;执行[“$L”!=“$PL”&&“$PL”!=”]&&echo;回音“$L”;PL=“$L”;完成
1
1
1
2
2
2
当列中的值更改时,我想插入一个空行:
1
1
1
<- blank line
2
2
2
1
1.
1.
读L时;执行[“$L”!=“$PL”&&“$PL”!=”]&&echo;回音“$L”;PL=“$L”;完成
awk(1)似乎是这个问题的明显答案:
#!/usr/bin/awk -f
BEGIN { prev = "" }
/./ {
if (prev != "" && prev != $1) print ""
print
prev = $1
}
我建议使用awk:
awk -v i=1 'NR>1 && $i!=p { print "" }{ p=$i } 1' file
在第一行之后的任何一行上,如果第i列的值与前一列的值不同,则打印一个空行。始终设置p
的值。末尾的1
计算结果为true,这意味着awk打印该行i
可以设置为您选择的列号。您也可以使用SED执行此操作:
sed '{N;s/^\(.*\)\n\1$/\1\n\1/;tx;P;s/^.*\n/\n/;P;D;:x;P;D}'
附有说明的长版本是:
sed '{
N # read second line; (terminate if there are no more lines)
s/^\(.*\)\n\1$/\1\n\1/ # try to replace two identical lines with themselves
tx # if replacement succeeded then goto label x
P # print the first line
s/^.*\n/\n/ # replace first line by empty line
P # print this empty line
D # delete empty line and proceed with input
:x # label x
P # print first line
D # delete first line and proceed with input
}'
关于使用(GNU)SED,我喜欢的一点是(您的问题中不清楚它是否对您有用)您可以使用-I开关轻松地应用更改,例如
sed-i'{N;s/^\(.*\)\N\1$/\1\N\1/;tx;p;s/^.*\N/\N/;p;D;:x;p;D}文件
您可以在Awk中使用getline
函数将当前行与以下行匹配:
awk '{f=$1; print; getline}f != $1{print ""}1' file