Operating System - Linux
1753809 Members
8381 Online
108805 Solutions
New Discussion юеВ

need to add trailing spaces to match fixed character length

 
sathis kumar
Frequent Advisor

need to add trailing spaces to match fixed character length

Hello,

My i/p file (INPUT) has 2 lines. First line has 41 chars and the second one has 100 chars.
I need to have fixed character length (145) in the all the lines of that file. I tried the below script but unable to pass the varaible 'j' in the for loop.

i=0;
while read line
do
count=`echo $line | wc -c`
j=`expr 145 - $count`
echo "Char count is $count \n"
echo $line | awk '{ printf $1
for (k=0; k<$j; k++) printf " " } ' >> OUTPUT
done < INPUT

NOTE : error comes due to "k<$j" used ...

Can anybody please help me in this?

Thanks & Regards,
Sathis Kumar.B

4 REPLIES 4
Steven Schweda
Honored Contributor

Re: need to add trailing spaces to match fixed character length

I only know simple-minded, crude ways to do
such things.

td176> str='abc'

td176> echo ">${str}<"
>abc<

td176> strp=` echo " $str" | sed -e 's/.*\(......\)$/\1/' `

td176> echo ">${strp}<"
> abc<


But I have fun.
Mounaam
Trusted Contributor

Re: need to add trailing spaces to match fixed character length

Hi,

example with Posix shell:
$ typeset -R8 a=123
$ typeset -L8 b=123
Result:
$ echo "|$a|\n|$b|"
| 123|
|123 |

For your case:
$ typeset -L145 l
$ while read l;do echo $l;done < input > output
Hein van den Heuvel
Honored Contributor

Re: need to add trailing spaces to match fixed character length

Just use awk or perl or printf in the loop.


$IFS=""
$while read line
do
printf "%-145s\n" $line
done < INPUT

or

$ awk '{printf("%-80s\n",$0)}' INPUT > OUTPUT

or by adding a piece of string in perl:

$ perl -pe '$pad=q( )x(145-length); s/$/$pad/e' INPUT > OUTPUT


so many ways....

All so much better than printing a character at a time until done.

hth.
Hein.






Peter Nikitka
Honored Contributor

Re: need to add trailing spaces to match fixed character length

Hi,

leaving the best solution of Mounaam beside, your mistake is the mixing of a shell variable $j into awk, which is not possible in the way you did it.
1) Splice up the command string the shell parses
... | awk '{ printf $1
for (k=0; k<'$j'; k++) printf " " } ' ...
2) Supply an awk variable
... | awk -v j=$j '{ printf $1
for (k=0; k
There are other constructs in you awk which make your solution break:
1) Dealing just with the printf() function without '\n' in the strings will result in one long line.
2) Having spaces in your line, only a part of the input will be copied.

If this awk is part of a larger processing, I suggest this approach:
awk '{printf($0);for(k=length($0);k<145;k++) printf(" ");printf("\n")}' input >output

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"