Cat

帶有標題和行號的貓?

  • February 5, 2015

我有這樣的文件

$ cat trapetz
x = 0:0.0001:7pi
plot(x, sin(x).*cos(x))
Area = trapz(x, sin(x).*cos(x))
$ cat simpson 
f = inline(sin(x).*cos(x));
Area2 = quad(f, 0, 7pi, 1e-16)

我想要這樣的東西

$ cat -b -t MISSING? trapetz simpson 
    traapetz 
    1  x = 0:0.0001:7pi
    2  plot(x, sin(x).*cos(x))
    3  Area = trapz(x, sin(x).*cos(x))
    simpson
    1  f = inline(sin(x).*cos(x));
    2  Area2 = quad(f, 0, 7pi, 1e-16)

如果有一些簡單的方法可以在那裡添加 wc 甚至更好:

$ find |tee |...|wc... I feel now reinventing the wheel, there must be some ready...
    traapetz: xyz chars
    1  x = 0:0.0001:7pi
    2  plot(x, sin(x).*cos(x))
    3  Area = trapz(x, sin(x).*cos(x))
    simpson: zyx chars
    1  f = inline(sin(x).*cos(x));
    2  Area2 = quad(f, 0, 7pi, 1e-16)

但我明白了

$ cat -b -t trapetz simpson 
    1  x = 0:0.0001:7pi
    2  plot(x, sin(x).*cos(x))
    3  Area = trapz(x, sin(x).*cos(x))
    4  f = inline(sin(x).*cos(x));
    5  Area2 = quad(f, 0, 7pi, 1e-16)

不是真的需要 cat,而是一些簡單的工具來共享和顯示上述程式碼片段,而不是 pastebin。我想要一些標準的命令行的東西。我正在嘗試為 codegolf.se 創建簡單的拼圖粘貼,以便人們可以輕鬆地重現事物……

一個非常粗略的 awk 實現:

BEGIN{
   OLDFILENAME="";
}
FNR==1{
   if (OLDFILENAME != "") {
       printf("#### Processed (chars: %s - lines: %s)\n", FWC, FLC);
   }
   printf("#### Processing: %s\n", FILENAME);
   OLDFILENAME=FILENAME;
   FWC=0;
   FLC=0;
}
{
   printf("%04d - %s\n", FNR, $0);
   FWC = FWC + length($0);
   FLC = FLC + 1;
}
END{
   if (OLDFILENAME != "") {
       printf("#### Processed (chars: %s - lines: %s)\n", FWC, FLC);
   }
}

執行awk -f AWKFILE trapetz simpson得到:

#### Processing: trapetz
0001 - x = 0:0.0001:7pi
0002 - plot(x, sin(x).*cos(x))
0003 - Area = trapz(x, sin(x).*cos(x))
#### Processed (chars: 70 - lines: 3)
#### Processing: simpson
0001 - f = inline(sin(x).*cos(x));
0002 - Area2 = quad(f, 0, 7pi, 1e-16)
#### Processed (chars: 57 - lines: 2)

快速外殼腳本:

#!/bin/sh
# usage: scriptname file1 file2 ...

for file in "$@"
do
   [ -f "$file" ] || continue
   set -- `wc "$file"`
   echo "${file}: lines $1 words $2 bytes $3"
   cat -b -t "$file"
done

它的行為類似於您的範例輸出,因此失去的文件將被忽略。

引用自:https://unix.stackexchange.com/questions/23528