
多数の行を含むファイルがあり、各行の長さを 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:
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 (旧称 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]
ありがとう。