Bash标准输出字符限制

Adr*_*ski 4 bash stdout file limit

如何限制重定向到文件的标准输出字符的数量?

kur*_*umi 6

其他方式(外部)

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/'
Run Code Online (Sandbox Code Playgroud)


Sie*_*geX 1

您可以使用命令替换来包装输出预重定向,然后使用偏移量参数扩展来限制字符数,如下所示:

#!/bin/bash

limit=20

out=$(echo "this line has more than twenty characters in it")
echo ${out::limit} > /path/to/file
Run Code Online (Sandbox Code Playgroud)

概念验证

$ limit=20
$ out=$(echo "this line has more than twenty characters in it").
$ echo ${out::limit}
this line has more t
Run Code Online (Sandbox Code Playgroud)

  • @sarnold *参数扩展* 似乎是最大的被低估/未知的功能,不仅是 `bash`,而且是*任何* POSIX 兼容 shell 的最大被低估/未知功能。我一次又一次地看到人们调用“basename”或“dirname”,这两者都可以使用参数扩展在本机 shell 语法中完成。请参阅[此处](http://mywiki.wooledge.org/BashFAQ/073),获取有关使用的良好链接以及关于 bash 的**优秀**网站。 (2认同)