1
bash中有一種方法可以在保留顏色代碼的同時獲取特定長度的子字符串(在終端中佔用#個字符)嗎?Bash - 使用顏色代碼獲取子字符串
我想我可以解釋一下我的意思是一些代碼更好(假裝大膽的手段綠色):
$ # One string is green and another is normal. $ green_string="\e[1;32mFoo bar baz buzz.\e[0m" $ normal_string=`echo -e $green_string | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g"` $ $ # Echo both of them out to show the difference $ echo -e $green_string Foo bar baz buzz. $ echo -e $normal_string Foo bar baz buzz. $ $ # Get a substring of both. $ green_sub=${green_string:0:11} $ normal_sub=${normal_string:0:11} $ $ # Since the special characters are a part of the string, the colored $ # substring (rightfully) has fewer printable characters in it. $ echo -e "$green_sub\e[0m" Foo $ echo -e $normal_sub Foo bar baz $ $ # Is there any built in way of doing something like this: $ green_sub=`some_method $green_string 11` $ normal_sub=`some_method $normal_string 11` $ echo -e "$green_sub\e[0m"; echo -e $normal_sub Foo bar baz Foo bar baz
對於我這樣的人,這裏的複製/粘貼版本:
green_string="\e[1;32mFoo bar baz buzz.\e[0m"
normal_string=`echo -e $green_string | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g"`
echo -e $green_string
echo -e $normal_string
green_sub=${green_string:0:11}
normal_sub=${normal_string:0:11}
echo -e "$green_sub\e[0m"
echo -e $normal_sub
# green_sub=`some_method $green_string 11`
# normal_sub=`some_method $normal_string 11`
# echo -e "$green_sub\e[0m"; echo -e $normal_sub
我爲了複製/粘貼演示的目的,這個功能需要ls的輸出並使其填滿整行終端(或更短):
function lsline {
color_out=$(ls --color=always | tr "\n" " ")
max_len=`tput cols`
cur_len=0
is_esc=0
# This is the build of the final string that will be printed out.
build=""
# This is the build of any escape sequence so I know not to
# include it in the substring count
esc_build=""
for ((i=0; i<${#color_out}; i++)); do
char="${color_out:$i:1}"
# Is there an easier way to check if a char is an escape character?
code=$(printf %x "'$char")
# Currently in an escape sequence, so don't count towards max length.
if [ "$is_esc" -eq "1" ]; then
esc_build="$esc_build$char"
if [ "$char" = "m" ]; then
is_esc=0
build="$build$esc_build"
esc_build=""
fi
elif [ "$code" = "1b" ]; then
# 27 is escape character.
is_esc=1
esc_build="$char"
else
# Not an escape sequence, so build our normal string and update
# the current substring length.
build="$build$char"
((cur_len++))
if [ "$cur_len" -eq "$max_len" ]; then
build="$build$(tput sgr0)"
break
fi
fi
done
echo "$build"
}
此代碼有效,但它是sooo slow。
請告訴我這樣做有一個更快/更簡單的方法!
這怎麼能適用於有多個顏色代碼的字符串呢? 「\ e [1; 32mGreen \ e [0m和\ e [1; 31mRed \ e [0m」 –
)實質上,您需要解析字符串,這不是任何shell語言的強項。對於彩色字符串應該是什麼樣子沒有特別的標準。這些字節不是標記標籤;它們只是終端的指令,以改變其顯示以下文本的方式。 – chepner