在 中bash
,给定一个包含ANSI CSI 代码(例如颜色)的任意字符串,我如何发出以正确颜色打印的可打印字符的子集?
例如,给定:
s=$'\e[0;1;31mRED\e[0;1;32mGREEN\e[0;1;33mYELLOW'
我该怎么做:
coloursubstr "$s" 0 5
coloursubstr "$s" 2 7
使用 bash 和 GNU grep:
coloursubstr() {
local string="$1" from="$2" num="$3"
local line i array=()
# fill array
while IFS= read -r line; do
[[ $line =~ ^([^m]+m)(.*)$ ]]
for ((i=0;i<${#BASH_REMATCH[2]};i++)); do
array+=("${BASH_REMATCH[1]}${BASH_REMATCH[2]:$i:1}")
done
done < <(grep -Po $'\x1b.*?m[^\x1b]*' <<< "$string")
# print array
for ((i=$from;i<$from+$num;i++)); do
printf "%s" "${array[$i]}"
done
echo
}
s=$'\e[0;1;31mRED\e[0;1;32mGREEN\e[0;1;33mYELLOW'
coloursubstr "$s" 0 5
coloursubstr "$s" 2 7
输出:
我假设所有颜色代码都以 开头\e
,以 结尾,m
并且文本以颜色代码为前缀。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句