我正在尝试使用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有谁有什么想法吗?
发布于 2015-07-05 02:37:07
这些是对齐的:每行都是60个字符的长度,向右对齐。尝试使用"%-60s“来向左对齐。
发布于 2015-07-05 02:40:03
对我来说,它打印出来是正确对齐的。要将其左对齐,请使用%-,例如:
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发布于 2015-07-05 03:56:48
我喜欢用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
}
mainhttps://stackoverflow.com/questions/31223956
复制相似问题