It is currently Mon, 08 Aug 2022 19:49:00 GMT

Author Message
 sed - same length for all lines

is it possible to write a sed script which makes all lines in a file the
same length?
When a line is shorter than the longest line then this line shall be
filled with whitespaces until it has the same length as the longest line
in the file.

Can you please give me an idea or a hint how to solve this problem.

Thank you very much


 Sun, 20 Jul 2008 18:55:48 GMT   
 sed - same length for all lines

You can do something like:

awk '
  NR > FNR {
    printf("%-*s\n", l, $0)
  length > l {l = length}' ./file.txt ./file.txt

(yes, provide the file twice. In the first pass, get the length
of the longest line, in the second, pad the lines with spaces).

You could also use a combination of dd conv=block and fold.


 Sun, 20 Jul 2008 19:14:24 GMT   
 sed - same length for all lines

You could do that in Perl:

perl -e'
@lines = map { chomp; $longest < length and $longest = length; $_ } <>;
print map sprintf( "%-*s\n", $longest, $_ ), @lines;
' yourfile

use Perl;

 Mon, 21 Jul 2008 11:24:32 GMT   
 sed - same length for all lines


data ={ |x| x.chomp }
len ={ |x| x.size }.max
data.each{ |x| puts x + " " * (len - x.size) }

 Mon, 21 Jul 2008 12:50:32 GMT   
 sed - same length for all lines

If this were an exercise where you are restricted to the use of no other
utilities apart from sed, then it can be done but is somewhat esoteric.

Implement this schema: first extract the longest line, then on a second
pass through your data pad each line with a fixed block of spaces but
immediately truncate it to your predetermined length.

This illustrates how to go about doing it using standard sed:

widest=`sed -n 's/././g;G;/^\(.*\)\n\(\1.*\)/!{s/\n.*//;h;};${g;p;}' file`
blanks=`echo "$widest"| sed 's/./ /g'`
sed 's/$/$blanks/;s/\('$widest'\).*/\1/' file

Not fully tested.
John Savage                   (my news address is not valid for email)

 Thu, 31 Jul 2008 08:06:43 GMT   
 sed - same length for all lines
correction: sed 's/$/'"$blanks"'/;s/\('$widest'\).*/\1/' file
John Savage                   (my news address is not valid for email)

 Sat, 02 Aug 2008 06:03:14 GMT   
   [ 6 post ] 

Similar Threads

1. sed expression for truncating line length

2. SED & line lengths

3. a SED script to find length of the longest line in a file

4. sed Max line length?

5. to all sed hackers - joining lines with sed

6. SED / Line / (Need to get data from searched line from specific char to char)

7. Sed: merging lines recursively depending on line pattern

8. SED: Converting 5 line script into 1 line script

9. what sed command to print the first line and the last line

Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group.
Designed by ST Software