gpt4 book ai didi

bash - 缩进长行标准输出

转载 作者:行者123 更新时间:2023-12-02 16:57:13 24 4
gpt4 key购买 nike

假设我有一个标准的 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 -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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com