如何跳过与模式匹配的行上的打印。剩余的行将与相应的行一起显示,printf
直到新行与另一个模式匹配。
我想要的是Wht:
、Grn:
和Blu:
代码来指示后续文本的颜色。因此它们不会被输出,而是用于更改颜色设置。
到目前为止,这是我所拥有的,它可以处理着色,但没有做我想要的事情:
theone ()
{
printf '%s\n' "$@" \
| while IFS="" read -r vl; do
if [[ "$vl" =~ ^[[:space:]]*Wht:[[:space:]]*$ ]]; then
printf '%s%s%s\n' "${wht}" "$vl" "${rst}"
elif [[ "$vl" =~ ^[[:space:]]*Grn:[[:space:]]*$ ]]; then
printf '%s%s%s\n' "${grn}" "$vl" "${rst}"
elif [[ "$vl" =~ ^[[:space:]]*Blu:[[:space:]]*$ ]]; then
printf '%s%s%s\n' "${blu}" "$vl" "${rst}"
else
printf '%s%s%s\n' "${wht}" "$vl" "${rst}"
fi
done
}
这是一个例子
var="
Grn:
Some lines in green
More green lites
Green light again
Blu:
Now turning to blue
And more blue"
theone "$var"
结果将是
Some lines in green
More green lites
Green light again
Now turning to blue
And more blue
答案1
这是解决该问题的一种 POSIX 兼容方法:
#!/bin/sh
# Colour codes
grn=$(tput setaf 2) blu=$(tput setaf 4) wht=$(tput setaf 7)
rst=$(tput sgr0)
theone()
{
printf '%s\n' "$@" |
while IFS= read -r vl
do
# Strip leading and trailing space
ns=${vl##[[:space:]]}
ns=${ns%%[[:space:]]}
case "$ns" in
# Look for a colour token
Wht:) use="$wht" ;;
Grn:) use="$grn" ;;
Blu:) use="$blu" ;;
# Print a line
*) printf "%s%s%s\n" "${use:-$wht}" "$vl" "$rst" ;;
esac
done
}
如果您正在使用,bash
您也可以将颜色代码放入关联数组中并在其中查找条目,而不是使用构造case … esac
:
#!/bin/bash
theone()
{
# Colour codes
declare -A cc=(
['Grn:']=$(tput setaf 2)
['Blu:']=$(tput setaf 4)
['Wht:']=$(tput setaf 7)
)
local rst=$(tput sgr0)
printf '%s\n' "$@" |
while IFS= read -r vl
do
# Strip spaces
ns=${vl//[[:space:]]/}
# Look for a defined token
if [[ -v cc[$ns] ]]
then
# Assign the next colour
use=${cc[$ns]}
else
# Print a line
printf "%s%s%s\n" "${use:-${cc['Wht:']}}" "$vl" "$rst"
fi
done
}