开发者

Right align file

I need function for right-aligning my file. Could you give m开发者_JAVA技巧e some hint or suggestion? Thanks.


while read line
do
  printf '%80s\n' "$line"
done < infile.txt > outfile.txt


I can only think of one way to answer this question:

 % ./4168932.awk ./4168932.awk        
                      #!/usr/bin/awk -f

                                      {
                           a[++n] = $0;
            if (length(a[n]) > width) {
                   width = length(a[n])
                                      }
                                      }

                                  END {
              format = "%" width "s\n";
    for (line = 1; line <= n; ++line) {
                 printf format, a[line]
                                      }
                                      }


Edit:

Actually, you don't need to reverse the lines:

printf -v spaces "%80s" " "; man rev | sed "s/^/$spaces/;s/.*\(.\{80\}\)\$/\1/"

Original:

Reverse the lines, pad them, truncate them and reverse them back.

man rev | rev | sed '1{x;s/^$/          /;s/^.*$/&&&&&&&&/;x};G;s/^\(.\{81\}\).*$/\1/;s/\n//' | rev

Output:

  REV(1)                    BSD General Commands Manual                   REV(1)

                                                                            NAME
                                          rev — reverse lines of a file or files

                                                                        SYNOPSIS
                                                                  rev [file ...]

                                                                     DESCRIPTION
              The rev utility copies the specified files to the standard output,
        reversing the order of characters in every line.  If no files are speci‐
                                               fied, the standard input is read.

                                                                    AVAILABILITY
           The rev command is part of the util-linux-ng package and is available
                       from ftp://ftp.kernel.org/pub/linux/utils/util-linux-ng/.

  BSD                             March 21, 1992                             BSD

Here's another way to do the same thing:

printf -v spaces "%80s" " "; man rev | rev | sed "s/\$/$spaces/;s/^\(.\{80\}\).*$/\1/" | rev


You will need to detect the maximum length of a line in your file, and to write a function to pad lines with spaces to this length.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜