2017-05-02 39 views
2

bash中,給定包含(例如顏色)的任意字符串,如何發出可打印字符的子集,並以正確的顏色打印?bash:使用ANSI代碼從字符串中發出n個可打印字符

例如,給出:

s=$'\e[0;1;31mRED\e[0;1;32mGREEN\e[0;1;33mYELLOW' 

enter image description here

我怎麼做這樣的事情:

coloursubstr "$s" 0 5 

enter image description here

coloursubstr "$s" 2 7 

enter image description here

+0

試着在https://codegolf.stackexchange.com/上提問! –

回答

2

使用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 

輸出:

REDGR
DGREENY

我假定所有的顏色代碼開始\e,一端與m和文本通過顏色代碼前綴。

-1

部分答案,(與幻數特定設備,而不是在所有普通):

echo "${s:0:23}" 
echo "${s:0:9}${s:11:25}" 

輸出:

REDGR

DGREENY

+1

請重新閱讀:'給定任意字符串'。 –

+0

@TomHale,同樣,重新閱讀'部分','不...通用'。雖然上述內容對這個Q來說不是一個令人滿意的答案,但它可能是第一步或跳板的想法,並且它的工作原理可能對某些讀者有用。 – agc