使用printf时,行未正确对齐

时间:2015-07-04 18:31:53

标签: bash printf

我正在尝试使用printf在BASH脚本中打印行。我知道"%60s"对齐文本但出于某种原因我得到了这个输出:

Welcome root! Please select an option:

                         [1] Install startup repos
                           [2] Update sources.list
                             [3] Edit sources.list
                            [4] Reset sources.list

这是我的剧本:

   function main () {
       main_header
       printf "%20s\n"  "${YELLOW}Welcome ${USER}! Please select an option:"
       printf "%60s\n"  "${GREEN}[1] ${YELLOW}Install new sources.list"
       printf "%60s\n"  "${GREEN}[2] ${YELLOW}Update sources.list"
       printf "%60s\n"  "${GREEN}[3] ${YELLOW}Edit sources.list"
       printf "%60s\n"  "${GREEN}[4] ${YELLOW}Reset sources.list"
    }

    main

有没有人有任何想法?

3 个答案:

答案 0 :(得分:2)

这些是对齐的:每行是60个字符,长到右边。尝试使用"% - 60s"而是向左证明。

答案 1 :(得分:1)

对我而言,它打印出右对齐。要左对齐,请使用% - ,例如:

function main () {
   main_header
   printf "%-20s\n"  "${YELLOW}Welcome ${USER}! Please select an option:"
   printf "%-60s\n"  "${GREEN}[1] ${YELLOW}Install new sources.list"
   printf "%-60s\n"  "${GREEN}[2] ${YELLOW}Update sources.list"
   printf "%-60s\n"  "${GREEN}[3] ${YELLOW}Edit sources.list"
   printf "%-60s\n"  "${GREEN}[4] ${YELLOW}Reset sources.list"
}

打印

Welcome ! Please select an option:
[1] Install new sources.list
[2] Update sources.list
[3] Edit sources.list
[4] Reset sources.list

(不包括有关main_header的错误消息:找不到命令)

要对齐"请"下的后续行,确定缩进的长度,创建一个带有缩放该长度的格式字符串的变量,并在行的printf语句中使用该格式字符串进行缩进。使用格式字符串的技巧是首先写入一个空字符串以使缩进等于字段宽度,然后将所需的字符串写入同一行。例如,

indentString="${YELLOW}Welcome ${USER}! "
indentLength=${#indentString}
indentFormat="%${indentLength}s%s\n"
printf "$indentFormat" "" "${GREEN}[1] ${YELLOW}Install new sources.list"

将它放在main()中会变成:

function main () {
   indentString="${YELLOW}Welcome ${USER}! "
   indentLength=${#indentString}
   indentFormat="%${indentLength}s%s\n"
   main_header
   printf "%-20s\n" "${YELLOW}Welcome ${USER}! Please select an option:"
   printf "$indentFormat" "" "${GREEN}[1] ${YELLOW}Install new sources.list"
   printf "$indentFormat" "" "${GREEN}[2] ${YELLOW}Update sources.list"
   printf "$indentFormat" "" "${GREEN}[3] ${YELLOW}Edit sources.list"
   printf "$indentFormat" "" "${GREEN}[4] ${YELLOW}Reset sources.list"
}

打印:

Welcome training! Please select an option:
                  [1] Install new sources.list
                  [2] Update sources.list
                  [3] Edit sources.list
                  [4] Reset sources.list

答案 2 :(得分:0)

我喜欢使用pr缩进。有时我使用remote_function | tr -pro 3清楚地看到远程输出 在您使用pr的情况下,将生成以下代码:

function options () {
        echo "${GREEN}[1] ${YELLOW}Install new sources.list"
        echo "${GREEN}[2] ${YELLOW}Update sources.list"
        echo "${GREEN}[3] ${YELLOW}Edit sources.list"
        echo "${GREEN}[4] ${YELLOW}Reset sources.list"
}

function main () {
        printf "%20s\n"  "${YELLOW}Welcome ${USER}! Please select an option:"
        options | pr -tro 17
}

main