Append spaces the rows to make it into a required fixed length file

I want to make a script to read row by row and find its length. If the length is less than my required length then i hav to append spaces to that paritucular row. Each row contains special characters, spaces, etc.

For example my file contains ,

12345    abcdef
234    abcde
89012  abcdefgh

Each row should be of length 15, if any row is less than 15 then for the remaining length spaces should be appended.

Hey,

Welcome to The UNIX and Linux Forums,

Please use code tags for data samples and codes. code tag button look like

You should use printf to adjust the length of each lines.

Try something like this,

awk -v l="15" '{s="%-"l"s\n";printf(s,$0);}' input_file

Cheers,
Ranga:)

1 Like

This works great; can you please explain how this works

# cat file
12345 abcdef
234 abcde
89012 abcdefgh


# awk -v l="15" '{s="%-"l"s\n";printf(s,$0);}' file > temp; cat temp > file


# awk '{ if (length($0) > max) max = length($0) }
END { print max }' file
15

Please check the output of my command and not the input file.

# awk -v l="15" '{s="%-"l"s\n";printf(s,$0);}' file|awk '{print length($0);}'
15
15
15

Cheers,
Ranga:)

---------- Post updated at 05:29 AM ---------- Previous update was at 04:58 AM ----------

sathyaonnuix,

We can adjust the colunm/row length by using the printf functions format specifier.

printf("%-20s",line); -> This will fill spaces when the field is lesser than 20 characters.

Cheers,
Ranga:)

1 Like

Wow thats clear, thanks Ranga

I need to pass the length and file name as parameters. Please help how to change the below code as per that,

 
awk -v l="15" '{s="%-"l"s\n";printf(s,$0);}' file > temp;

You don't necessarily need to use awk, can be done with shell (bash, ksh) builtin printf :

$ FILE=file
$ LENGTH=15
$ while read LINE; do printf "%-"$LENGTH"s\n" "$LINE"; done <"$FILE"
12345 abcdef   
234 abcde      
89012 abcdefgh 

Remove - sign in front of $LENGTH if you want it right justified.

I need to pass the values as external parameters, i.e., at runtime i want pass the values.

So - assign LENGTH and FILE a runtime, or, replace by e.g. $1 and $2.

The below code do not appened spaces as many as my required length. When i gave length as 285, it append spaces upto 251 only. When i use printf command it shows 285.

But when i write the output to a file, in that the length is only 251 but not 285.

 
awk -v l="$1" '{s="%-"l"s\n";printf(s,$0);}' input_file

Any proposal above does work on my system, giving lines of 285 chars in total. Do you have limitations on line length or similar?
Post samples of input & output files.