- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有一个标准的 80 列终端,执行带有长行输出的命令(即来自 ls
的标准输出)分成两行或更多行,并且想要缩进我所有的续行bash 标准输出。
缩进应该是可配置的,1 或 2 或 3 或任何空格。
由此
lrwxrwxrwx 1 root root 24 Feb 19 1970 sdcard ->/storage/emula
泰德/遗产/
对此
lrwxrwxrwx 1 root root 24 Feb 19 1970 sdcard ->/storage/emula
ted/legacy/
阅读此 Indenting multi-line output in a shell script所以我尝试通过管道传输 | sed 's/^//'
但给了我完全相反的结果,缩进了第一行而不是后续行。
理想情况下,我会在 profile.rc 或其他任何地方放置一个脚本,这样每次我打开交互式 shell 并执行任何命令时,长输出都会缩进。
最佳答案
我会为此使用 awk。
awk -v width="$COLUMNS" -v spaces=4 '
BEGIN {
pad = sprintf("%*s", spaces, "") # generate `spaces` spaces
}
NF { # if current line is not empty
while (length > width) { # while length of current line is greater than `width`
print substr($0, 1, width) # print `width` chars from the beginning of it
$0 = pad substr($0, width + 1) # and leave `pad` + remaining chars
}
if ($0 != "") # if there are remaining chars
print # print them too
next
} 1' file
一行:
awk -v w="$COLUMNS" -v s=4 'BEGIN{p=sprintf("%*s",s,"")} NF{while(length>w){print substr($0,1,w);$0=p substr($0,w+1)} if($0!="") print;next} 1'
正如@Mark 在评论中建议的那样,您可以将其放入函数中并将其添加到 .bashrc
以便于使用。
function wrap() {
awk -v w="$COLUMNS" -v s=4 'BEGIN{p=sprintf("%*s",s,"")} NF{while(length>w){print substr($0,1,w);$0=p substr($0,w+1)} if($0!="") print;next} 1'
}
用法:
ls -l | wrap
Ed Morton 根据要求编辑:
与上面的 oguzismails 脚本非常相似,但应该与 Busybox 或任何其他 awk 一起工作:
$ cat tst.awk
BEGIN { pad = sprintf("%" spaces "s","") }
{
while ( length($0) > width ) {
printf "%s", substr($0,1,width)
$0 = substr($0,width+1)
if ( $0 != "" ) {
print ""
$0 = pad $0
}
}
print
}
$
$ echo '123456789012345678901234567890' | awk -v spaces=3 -v width=30 -f tst.awk
123456789012345678901234567890
$ echo '123456789012345678901234567890' | awk -v spaces=3 -v width=15 -f tst.awk
123456789012345
678901234567
890
$ echo '' | awk -v spaces=3 -v width=15 -f tst.awk
$
第一个测试用例是为了表明您没有在全角输入行之后打印空白行,第三个是为了表明它不会删除空白行。通常我会使用 sprintf("%*s",spaces,"")
来创建 pad
字符串,但我在评论中看到它不起作用在您使用的明显非 POSIX awk 中。
关于bash - 缩进长行标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55966413/
我正在使用 grep 仅返回多个文件中模式 (-o) 之间的字符串,例如 grep -i -r -o 'Rows="[^#][^"]*"' * 我希望它在第一个匹配模式后停止,我试过 grep -m
我是一名优秀的程序员,十分优秀!