以某种模式表示输出



我有一个以形式输入数据的文件

cell1
C
input;
Cp
input;
D
input;
Q
output;
Qn
output;
cell2 
Cp
input;
D
input;
Q
output;
cell3 
A1
input;
B
input;
B1
input;
S
output;
Sn
output;

我想要我的输出数据如下

cell1
input C;
input CP;
input D;
output Q;
output Qn;
cell2 
input CP;
input D;
output Q;
cell3 
input A1;
input B;
input B1;
output S;
output Sn;

我用了代码

awk -vRS='noutput;n' '{printf("%sn",$1); for(i=2;i<NF;i+=2)printf("input %s;n",$i); printf("output %s;n",$NF)}' file 

当Data只有一个输出行时,此代码运行良好。如果数据中有两个输出行,那么我如何修改代码。

完全基于您显示的示例,您可以尝试以下操作吗。在GNUawk中编写和测试(虽然应该在任何awk中工作,但在GNU one中测试(

awk '
/^cell/{
print
count=""
next
}
++count==1{
val=$0
next
}
count==2{
sub(/;$/,OFS val"&")
print
val=count=""
}' Input_file

要将输出保存到Input_file本身,请尝试以下操作。

awk '
/^cell/{
print
count=""
next
}
++count==1{
val=$0
next
}
count==2{
sub(/;$/,OFS val"&")
print
val=count=""
}' Input_file > temp && mv temp Input_file

解释:添加以上详细解释。

awk '                   ##Starting awk program from here.
/^cell/{                ##Checking condition if line starts from cell then do following.
print                 ##Printing current line here.
count=""              ##Nullifying count here.
next                  ##next will skip all further statements from here.
}
++count==1{             ##Checking condition if count is 1 then do following.
val=$0                ##Assigning $0 to val now.
next                  ##next will skip all further statements from here.
}
count==2{               ##Checking condition if count is 2 then do following.
sub(/;$/,OFS val"&")  ##Substituting last semi colon in line with OFS val and ; itself here.
print                 ##Printing current line here.
val=count=""          ##Nullifying values here.
}' Input_file           ##Mentioning Input_file names here.

这里有一个。

$ awk '
/^cell/                   # just output cell*
/^(input|output)/ {       # input and output special treatment
sub(/.$/, " " p "&")  # this probably causes problems if your
print                 # data is different from the sample
next
}
{
p=$0                   # oythers get buffered
}' file

输出:

cell1
input C;
input Cp;
input D;
output Q;
output Qn;
cell2 
input Cp;
input D;
output Q;
cell3 
input A1;
input B;
input B1;
output S;
output Sn;

另一个简单的awk

$ awk -F";" ' /^cell/ { print ; next } { a=$1; getline; print $1, a ";" } ' nehac.txt
cell1
input C;
input Cp;
input D;
output Q;
output Qn;
cell2
input Cp;
input D;
output Q;
cell3
input A1;
input B;
input B1;
output S;
output Sn;
$

这里是另一个实现相同功能的gnu awk

awk -v RS='n(input|output);n' '{
b=1
if ($1 ~ /^cell[0-9]/) {
print $1
++b
} 
for (i=b; i<=NF; ++i)
printf "%s", gensub(/;n$/, " " $i "&", "1", substr(RT,2))
}' file
cell1
input C;
input Cp;
input D;
output Q;
output Qn;
cell2
input Cp;
input D;
output Q;
cell3
input A1;
input B;
input B1;
output S;
output Sn;

最新更新