Hi all;

I'm having headache on append one line to another based on the fix position.Hope u guys can help.

All i need to do is append the line that start with '3' to a line which start with '1' and the position for line 3 that i need to append is 22.

The original file look like this:

1CSTN0012008010312
2A45021906080120070303131709000017600
2S45333282010520020065411701000017600
2Z30092614090520020065635811000026400
2Z21094701020220020065649305000019800
2S35343116010420020065650001000008800
2S35344198010120020065651208000006600
2S45333998010620020065702107000008800
2S35344254010220020065704708000013200
2D93688321010220020065708106000006600
2D93686199010420020065710405000009900
2K40052945050820020065714210000004400
2U30030159060220070304010210000013200
30000012000152900

I need to rearrange the file to make it look like this:

1CSTN0012008010312 30000012000152900
2A45021906080120070303131709000017600
2S45333282010520020065411701000017600
2Z30092614090520020065635811000026400
2Z21094701020220020065649305000019800
2S35343116010420020065650001000008800
2S35344198010120020065651208000006600
2S45333998010620020065702107000008800
2S35344254010220020065704708000013200
2D93688321010220020065708106000006600
2D93686199010420020065710405000009900
2K40052945050820020065714210000004400
2U30030159060220070304010210000013200

For your information the length for line that start with '1' is not fixed,it can be less than 21 character.

I'm having a problem when the length of the line (that starts with '0') is 21.
I try to use if ... else but got error msg. This is the script that i used

cat CSTN001.dat | awk '
/^1/ { line0 = $0}
{
if ( length(line0) < 21 )

FS=" "; for (i=1; i<(21-(length($0))); i++) FS=FS " ";
/^1/ { sub(/1/, "0") }
/^3/ { line1 = $0 }
/^0/ { $NF = ($NF FS line1) }
{ x[FNR] = $0 }
END{
for (i=1; i<=FNR; i++)
if (x[i] ~ /^0/)
print x[i]
for (j=1; j<=FNR; j++)
if (x[j] !~ /^[03]/)
print x[j]
}

else
/^1/ { sub(/1/, "0") }
/^3/ { line1 = $0 }
{ x[FNR] = $0 }
END{
for (i=1; i<=FNR; i++)
if (x[i] ~ /^0/)
print x[i] line1
for (j=1; j<=FNR; j++)
if (x[j] !~ /^[03]/)
print x[j]
}
}
' > CSTN001.new

Someone pls help...Thank you in advance

Hi all;

Already got the solution for this problem.
For those who have similar problem like this you can use this script:

awk '
/^1/ { s=$0 }
/^3/ {
if ( s == "" ) next
printf "%-21s%s\n",s,$0
s=""
}
' $INFILE

I got the answer from one of the members from other forum and it works perfectly...(Tq Ramesh)

This article has been dead for over six months. Start a new discussion instead.