Reputation: 471
I have a single column of a file having many blocks and the blocks are separated by the >
symbol.
I want to resize all blocks to the same highest length by appending zero below them.
My file is given below:
file.txt
>
1.0
2.4
3.5
4.5
>
1.2
3.3
>
2.4
2.5
2.5
and my expected output is given below
>
1.0
2.4
3.5
4.5
>
1.2
3.3
0.0
0.0
>
2.4
2.5
2.5
0.0
I am trying to write a script, but it fails:
#!/bin/sh
for file in `cat file.txt`
do
awk '{print $1+0}' $file
done
Upvotes: 1
Views: 78
Reputation: 784898
You may try this single-pass awk
also:
awk '$0==">"{if (c && c>max) max=c; ++n; c=0; next} {r[n][++c]=$0} END {for (i=1; i<=n; ++i) {print ">"; for (j=1; j<=max; ++j) print (r[i][j] == "" ? "0.0" : r[i][j])}}' file
>
1.0
2.4
3.5
4.5
>
1.2
3.3
0.0
0.0
>
2.4
2.5
2.5
0.0
To make it more readable:
awk '$0==">" {
if (c && c>max)
max = c
++n
c = 0
next
}
{
r[n][++c] = $0
}
END {
for (i=1; i<=n; ++i) {
print ">"
for (j=1; j<=(max>c?max:c); ++j)
print (r[i][j] == "" ? "0.0" : r[i][j])
}
}' file
Upvotes: 2
Reputation:
awk '
NR==FNR {
if (/^>/) c=0
if (++c>m) m=c
next
}
END {while (n-->0) print "0.0"}
/^>/{while (n-->0) print "0.0"; n=m} {n--}
1
' file file
Upvotes: 2
Reputation: 133428
Based on your shown samples, could you please try following. Written and tested with shown samples in GNU awk
.
awk '
FNR==NR{
if($0~/^>/){
max=(max>val?max:val)
val=""
next
}
val++
next
}
/^>/{
if(FNR>1){
while(count++<max){ print "0" }
}
count=""
print
next
}
{
print
count++
}
END{
while(count++<max){ print "0" }
}' Input_file Input_file
For shown samples output will be as follows.
>
1.0
2.4
3.5
4.5
>
1.2
3.3
0
0
>
2.4
2.5
2.5
0
Explanation: Adding detailed explanation for above.
awk ' ##Starting awk program from here.
FNR==NR{ ##Checking condition if FNR==NR here.
if($0~/^>/){ ##Checking condition if line starts from > then do following.
max=(max>val?max:val) ##Assigning max value as per max>val then assign it to max else keep it as val value.
val="" ##Nullify val here.
next ##next will skip all further statements from here.
}
val++ ##Increasing val with 1 here.
next ##next will skip all further statements from here.
}
/^>/{ ##Checking condition if line starts with >
if(FNR>1){ ##Checking condition if this is not first line.
while(count++<max){ print "0" } ##Printing 0 till count is equal to max.
}
count="" ##Nullify count here.
print ##Printing current line here.
next ##next will skip all further statements from here.
}
{
print ##Printing current line here.
count++ ##Increasing count with 1 here.
}
END{ ##Starting END block of this program from here.
while(count++<max){ print "0" } ##Printing 0 till count is equal to max.
}' Input_file Input_file ##Mentioning Input_file names here.
Upvotes: 2