mah*_*mah 4 linux text-processing
I have a file with many lines, and I want to trim each line to be 80 characters in length. How could I do this?
我已经过滤掉了短于 80 个字符的行,所以现在我留下了一个长度超过 80 个字符的文件,我想修剪每一行,以便全部都是 80。换句话说,我想保留每行的前 80 个字符并删除该行的其余部分。
jes*_*e_b 12
您可以使用以下cut命令:
cut -c -80 file
Run Code Online (Sandbox Code Playgroud)
与grep:
grep -Eo '.{80}' file
Run Code Online (Sandbox Code Playgroud)
使用AWK:
awk '{print substr($0,1,80)}' file.txt
Run Code Online (Sandbox Code Playgroud)
使用切割:
cut -c -80 file.txt
Run Code Online (Sandbox Code Playgroud)
使用colrm:
colrm 81 file.txt
Run Code Online (Sandbox Code Playgroud)
使用sed:
sed 's/^\(.\{80\}\).*$/\1/' file.txt
Run Code Online (Sandbox Code Playgroud)
使用grep:
grep -Eo '.{80}' file.txt
Run Code Online (Sandbox Code Playgroud)
小智 5
要剪切(截断)文件的每一行(并在当前控制台中输出),请使用:
cut -c -80 infile # cut only counts bytes (fail with utf8)
grep -o '^.\{1,80\}' infile
sed 's/\(^.\{1,80\}\).*/\1/' infile
Run Code Online (Sandbox Code Playgroud)
如果您想要在第 80 个字符处插入换行符并将长度超过 80 个字符的每行拆分为更多行,请使用:
fold -w 80 infile # fold, like cut, counts bytes.
Run Code Online (Sandbox Code Playgroud)
如果您只想在空格(整个单词)处分割,请使用:
fold -sw 80 infile
Run Code Online (Sandbox Code Playgroud)
>outfile对于上述所有解决方案,请在任何命令末尾重定向到其他文件(不要使用相同的名称,这将不起作用),以将结果存储在outfile. 例子:
fold -sw 80 infile > outfile
Run Code Online (Sandbox Code Playgroud)