2010-11-12 121 views
1

我需要右對齊我的文件的函數。你能給我一些提示或建議嗎? 謝謝。右對齊文件

+4

請遵循[general](http://tinyurl.com/so-hints)問題[準則](htt p://meta.stackexchange.com/q/10812):陳述任何特殊的限制,展示你到目前爲止已經嘗試過的東西,並詢問具體是什麼讓你感到困惑。 – 2010-11-12 20:55:59

回答

0

您需要檢測文件中某一行的最大長度,並編寫一個函數來填充具有此長度的空格。

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

編輯:

其實,你並不需要扭轉線:

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

原文:

反轉線,墊他們,截斷他們並將他們撤回。

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

輸出:

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 

這裏的另一種方式做同樣的事情:

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

我只能想到的一種方式來回答這個問題:

% ./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] 
             } 
             } 
+0

**艱難的人羣!** – Johnsyweb 2010-11-13 21:32:56