在bash脚本中,我想写一些类似的东西:
=====================================
= Doing something in THIS_DIRECTORY =
=====================================
实际上在我的脚本中我使用:
echo "====================================="
echo "= Doing something in $VARIABLE ="
echo "====================================="
仅当$VARIABLE
值的长度合适时才有效,否则会出现错位,如下所示:
=====================================
= Doing something in THIS_IS_ANOTHER_DIRECTORY =
=====================================
如何动态更改上下字符串的长度以保持中间行的长度相同?
答案 0 :(得分:6)
VARIABLE="foobar"
X="= Doing something in $VARIABLE ="
echo "${X//?/=}"
echo "$X"
echo "${X//?/=}"
输出:
============================= = Doing something in foobar = =============================
答案 1 :(得分:3)
这可能适合你(GNU sed):
sed 'h;s/./=/g;H;G' <<<"= Doing something in $VARIABLE ="
编辑:
将模式空间(PS)中的原始字符串复制到保留空间(HS),用=
替换PS中的每个字符,然后将PS附加到HS,最后将HS附加到HS PS并打印出PS。
答案 2 :(得分:2)
一种方法是计算$ VARIABLE的长度,然后根据它来回显等于(=
)。
var=$(echo "= Doing something in ${variable} =")
equal=$(printf "%-"${#var}"s" "=")
echo "${equal// /=}"; echo ${var}; echo "${equal// /=}"
var
将包含中间行文字。
${#var}
将返回中间线的长度。
答案 3 :(得分:1)
你可以这样做:
writenchar() {
local length=$1
local char=$2
for (( i = 0; i < $length; ++i )); do
echo -n "$char"
done
}
您必须计算中间字符串的长度:
declare middleString="= Doing something in ${VARIABLE} ="
declare border=$(writenlchar "${#middleString}" '=')
并回应它:
echo "${border}"
echo "${middleString}"
echo "${border}"
由于它是一个循环,我将结果存储在变量中,因为它会花费更少。 如果您不想要,那么代码将如下所示:
writenlchar "${#middleString}" '='
echo ""
echo "${middleString}"
writenlchar "${#middleString}" '='
echo ""
空回声在这里转储换行符。
告诉我它是否有效(我没有测试)。
答案 4 :(得分:1)
另一种允许添加着色的方法
#!/bin/bash
function pretty_p {
# Pretty-print a header
echo -e "\e[00;32m"
for i in in $(seq 1 ${#1}); do printf "%s" "=";done;echo
echo $1
for i in in $(seq 1 ${#1}); do printf "%s" "=";done
echo -e "\e[00m"
}
VARIABLE="foobar"
X="= Doing something in $VARIABLE ="
pretty_p "$X"
输出(遗憾的是黑色 - 白色而非酷炫的grenish):
==============================
= Doing something in foobar =
==============================
答案 5 :(得分:1)
您可以将printf
与seq
一起使用,以扩展到所需的长度。
var="= Doing something in $VARIABLE ="
equals=$(printf "%0.s=" $(seq ${#var}))
printf "$equals\n$var\n$equals\n"