【发布时间】:2011-03-29 21:58:52
【问题描述】:
如何限制重定向到文件的标准输出字符数?
【问题讨论】:
如何限制重定向到文件的标准输出字符数?
【问题讨论】:
其他方式(外部)
echo $out| head -c 20
echo $out | awk '{print substr($0,1,20) }'
echo $out | ruby -e 'print $_[0,19]'
echo $out | sed -r 's/(^.{20})(.*)/\1/'
【讨论】:
您可以使用 Command Substitution 来包装输出预重定向,然后使用偏移量 Parameter Expansion 来限制字符数,如下所示:
#!/bin/bash
limit=20
out=$(echo "this line has more than twenty characters in it")
echo ${out::limit} > /path/to/file
$ limit=20
$ out=$(echo "this line has more than twenty characters in it").
$ echo ${out::limit}
this line has more t
【讨论】:
bash,而且是any POSIX兼容的shell。一次又一次地,我看到人们调用basename 或dirname,这两者都可以使用参数扩展在本机shell 语法中完成。请参阅 HERE 以获取有关使用的良好链接以及 bash 上的 great 站点。
您不能直接将其写入文件,但您可以通过sed 或head 等方式传递仅部分输出。或者正如@SiegeX 所说,在 shell 中捕获输出(但如果输出可能很大,我会对此保持警惕)。
【讨论】: