设置帮助部分的格式,将标志的说明放在一列中

设置帮助部分的格式,将标志的说明放在一列中

我创建了一个帮助部分,其中显示以下内容

-m         This is a very very very very very very very very very very
very very very very very very very very very very long sentence

我想拥有

-m         This is a very very very very very very very very very very
           very very very very very very very very very very long 
           sentence.

指定我想要 2 列?

答案1

这是我整理的一个函数,您可以使用它一次打印一个与帮助相关的项目。我使用了-m问题中的示例和长帮助字符串。该函数将第一列的宽度硬编码为 10,然后计算第二列的剩余空间。

#!/bin/bash

function printhelp() (
  c1width=10
  cols=$(tput cols)
  c2width=$((cols - c1width - 1))
  readarray -t lines < <(printf '%s' "$2" | fmt -w $c2width)
  for((line=0; line < ${#lines[*]}; line++))
  do
    if [ $line -eq 0 ]
    then
      col1="$1"
    else
      col1=" "
    fi
    printf "%-${c1width}s %-${c2width}s\n" "$col1" "${lines[line]}"
  done
)

optf='-m'
optd='This is a very very very very very very very very very very very very very very very very very very very very long sentence'
printhelp "$optf" "$optd"

50 列屏幕上的示例输出:

-m         This is a very very very very very
           very very very very very very very
           very very very very very very very
           very long sentence

在 80 列的屏幕上:

-m         This is a very very very very very very very very very very very
           very very very very very very very very very long sentence

在 130 列的屏幕上:

-m         This is a very very very very very very very very very very very very very very very very very very very very
           long sentence

在 150 列的屏幕上:

-m         This is a very very very very very very very very very very very very very very very very very very very very long sentence

答案2

这并不完全是您所需要的,但如果参数名称和描述不在同一行中,那么这是一个简单的解决方法。保留fmt第二行的缩进:

$ FOO="-m\n\tThis is a very very very very very very very very very very very very very very very very very very very very long sentence"

$ echo -e $FOO
-m
    This is a very very very very very very very very very very very very very very very very very very very very long sentence

$ echo -e $FOO | fmt 
-m
    This is a very very very very very very very very very very very
    very very very very very very very very very long sentence

答案3

该解决方案也适用于zsh

FLAG="-m VARIABLE"
DESCRIPTION="This is a very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long sentence"
DISTANCE_FLAG=3

WIDTH1=$(echo "$FLAG" | wc -c ) 
WIDTH2=$(($(tput cols)-$DISTANCE_FLAG -$WIDTH1 ))

paste <(echo $FLAG ) <(echo $DESCRIPTION | fold -sw $(( $(tput cols) -     $DISTANCE_FLAG -$WIDTH1     )) )| pr -t -e$(($DISTANCE_FLAG+$WIDTH1))

相关内容