Remove new line character and add space to convert into fixed width file

I have a file with different record length. The file as to be converted into fixed length by appending spaces at the end of record. The length should be calculated based on the record with maximum length in the file.

If the length is less than the max length, the spaces should be appended before the new line character of that record.

 
Input File:
123
12345
1234
 
Output file:
123  
12345
1234 
 
Here the max record length is 5
awk 'NR==FNR{if(length($0) > maxlen){maxlen=length($0)}next}
{printf "|%-"maxlen"s|\n",$0}' file1.txt file1.txt 

Once you are confirm with o/p then remove "|" from the above code

1 Like

This is another way of doing it with awk which works for me:

awk 'BEGIN{while((getline f<FILENAME)>0){if(length(f)>l)l=length(f)}}{printf "%-"l"s\n",$0}' file
 
1 Like

The command is working fine but when i redirect the output to a file at the actual end of record i am able to see Control M(^M) charater.

 
awk 'NR==FNR{if(length($0) > maxlen){maxlen=length($0)}next}
{printf "%-"maxlen"s\n",$0}' file1.txt file1.txt > file2.txt
 
Output file: file2.txt
123^M<2space>
12345^M
1234^M<1space>

---------- Post updated at 06:16 PM ---------- Previous update was at 06:10 PM ----------

 
awk 'BEGIN{while((getline f<FILENAME)>0){if(length(f)>l)l=length(f)}}{printf "%-"l"s\n",$0}' file

The above code gives error as

expression for `<' redirection has null string value

You need to use files that are in unix-format, not DOS-format. To convert:

tr -d '\r' < infile > outfile
1 Like