將線條修剪到特定長度

將線條修剪到特定長度

我有一個包含許多行的文件,我想將每行的長度修剪為 80 個字元。我怎麼能這樣做呢?

我已經過濾掉了短於80 個字元的行,所以現在我留下了一個長度超過80 個字元的行的文件,我想修剪每一行,使所有行都恰好是80。保留每行的前 80 個字元並刪除該行的其餘部分。

答案1

您可以使用cut命令:

cut -c -80 file

grep

grep -Eo '.{80}' file

答案2

使用AWK:

awk '{print substr($0,1,80)}' file.txt

使用切:

 cut -c -80 file.txt

使用科爾姆:

colrm 81 file.txt

使用sed:

sed 's/^\(.\{80\}\).*$/\1/' file.txt

使用格列普:

grep -Eo '.{80}' file.txt

答案3

若要剪切(截斷)檔案的每一行(並在目前控制台中輸出),請使用:

cut -c -80 infile               # cut only counts bytes (fail with utf8)
grep -o '^.\{1,80\}' infile
sed 's/\(^.\{1,80\}\).*/\1/' infile

如果您想要在第 80 個字元處插入換行符號並將長度超過 80 個字元的每行拆分為更多行,請使用:

fold -w 80 infile            # fold, like cut, counts bytes.

如果您只想在空格(整個單字)處分割,請使用:

fold -sw 80 infile

>outfile對於上述所有解決方案,請在任何命令末尾重定向到其他檔案(不要使用相同的名稱,這將不起作用),以將結果儲存在outfile.例子:

fold -sw 80 infile > outfile

答案4

使用 Raku(née Perl6)

~$ raku -ne 'put ~$0 if m/ ^^(. ** 80) /;'

輸出:

the of and to in a is that for it as was with be by on not he i this are or his
the of and to in a is that for it as was with be by on not he i this are or his
the of and to in a is that for it as was with be by on not he i this are or his
the of and to in a is that for it as was with be by on not he i this are or his
[TRUNCATED]

上面的程式碼傳回一行的前 80 個字元(^^零寬度斷言意味著「行開始」)。如果該行太短,則不會傳回任何內容。回來取決於80 個字符,使用形式** 1..80.

捕獲的編號以 開頭$0。透過添加.chars到捕獲變數來獲取返回的字元數的讀數~$0

~$ raku -ne 'put ~$0.chars if m/ ^^(. ** 80) /;' ~/top50.txt
80
80
80
80
[TRUNCATED]

HTH。

https://raku.org

相關內容