LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Padding a character matrix with lines of unequal length (http://www.linuxquestions.org/questions/programming-9/padding-a-character-matrix-with-lines-of-unequal-length-4175455381/)

danielbmartin 03-24-2013 01:33 PM

Padding a character matrix with lines of unequal length
 
This is a learning exercise.

Have: a character matrix with lines of unequal length ...
(Note: $ signifies the end of each line)
Code:

ABC$
FGHIJ$
 LM $
PQR$

Want: a character matrix with lines of equal length, achieved by padding with blanks as necessary ...
(Note: $ signifies the end of each line)
Code:

ABC  $
FGHIJ$
 LM  $
PQR  $

I did this with awk ...
Code:

awk -F "" -v nc=$(wc -L < $Ragged)  \
  '{for (j=1;j<=nc;j++)
    {if (j<=NF) printf $j; else printf " ";}
    print ""}' $Ragged >$OutFile

Question: can the same transformation be made with sed?

Daniel B. Martin

colucix 03-24-2013 01:50 PM

Yes. This is a famous sed one-liner that basically explains the loops in sed:
Code:

sed -e :a -e 's/^.\{1,4\}$/& /;ta' file
To put the maximum number of characters in a line, you can do the same as in your example, using double quotes and arithmetic plus command substitution:
Code:

sed -e :a -e "s/^.\{1,$(($(wc -L < file)-1))\}$/& /;ta" file
You can find a detailed explanation here (see #26).

grail 03-24-2013 02:05 PM

You do know that from an awk point of view you could have just said:
Code:

awk  '{printf "%-5s\n",$0}' file

danielbmartin 03-24-2013 02:36 PM

Quote:

Originally Posted by grail (Post 4917856)
You do know that from an awk point of view you could have just said:
Code:

awk  '{printf "%-5s\n",$0}' file

I didn't know, but do now. Thank you!

I generalized your awk this way ...
Code:

echo "Pad all text with blanks to match longest line in the file"
echo "Based on method of LQ Guru grail"
echo; echo "Ragged ... ($ signifies end of line) ..."; cat -E $Ragged
awk  '{printf "%-'$(wc -L < $Ragged)'s\n",$0}' $Ragged >$OutFile
echo; echo "OutFile ...  ($ signifies end of line)"; cat -E $OutFile

... which produced this ...
Code:

Pad all text to match longest line in the file
Based on method of LQ Guru grail

Ragged ... ($ signifies end of line) ...
ABC$
FGHIJ$
 LM $
PQR$

OutFile ...  ($ signifies end of line)
ABC  $
FGHIJ$
 LM  $
PQR  $

Daniel B. Martin

danielbmartin 03-24-2013 02:59 PM

[QUOTE=colucix;4917849]
Code:

sed -e :a -e "s/^.\{1,$(($(wc -L < file)-1))\}$/& /;ta" file
Excellent. Instructive. Thank you for the reference. LQ teaches me every day!

SOLVED!

Daniel B. Martin


All times are GMT -5. The time now is 11:14 AM.