Alter Fixed Width File

Thank u so much .Its working fine as expected.

---------- Post updated at 03:41 PM ---------- Previous update was at 01:46 PM ----------

I need one more help.

I have another file(fixed length) that will get negative value (ex:-00000000003000) in postion (98 - 112) then i have to convert the value to 000000000000000(15 zeros-length is 15) and then print the entire record.

I have used substr($0,98,15) function and getting syntax error.

Please show your input data, and the output you want.

Please show what you tried.

I have tried the below commands.

awk '{ if ((rec_type = substr($0,98,15)) ~ /-/) (rec_type="000000000000000") print $0 }' InputFile 
awk '{ if (substr($0,98,15) ~ /-/) (substr($0,98,15)="000000000000000") print $0 }' InputFile

You are one infraction away from being set read-only. Please start using code tags.

awk doesn't work like that, it's for delimited files, not fixed-width ones. You can assign text to column numbers, but you can't assign it to the return of a function.

If you have GNU awk, you could do awk -v FIELDWIDTHS="width1 width2 width3 ..." '$5 ~ /-/ { $5="000000" } 1' inputfile outputfile , with 'width1' etc replaced by the widths of your columns, and 5 replaced by your column number... FIELDWIDTHS is a special variable GNU awk uses to deal with fixed width files.

1 Like
awk '{f1=substr($0,0,97); f2=substr($0,98,15); f3=substr($0,113); f2 = (f2 ~ /-/) ? "000000000000000" : f2; print f1 f2 f3}' InputFile
1 Like

There is also the sed / regex route:

sed 's/-[0-9]\{14\}\( *[0-9]\{1,\} *\)$/000000000000000\1/' file

==> Note that the file is still in DOS format, which means there is a CR character before the LF character at the end.

So first you would need to convert it to UNIX format:

tr -d '\r' < file > newfile

By using a single dot at the end to match the CR character, it can be made to work with a DOS format file:

sed 's/-[0-9]\{14\}\( *[0-9]\{1,\} *.\)$/000000000000000\1/' file

or

sed 's/-[0-9]\{14\}\( *[0-9]\{1,\} *.\{0,1\}\)$/000000000000000\1/' file

But the proper way is to convert first.

1 Like

Thanks everyone for the help ! The code is working as expected.