programing

출력에서 색상 제거

css3 2023. 4. 15. 09:12

출력에서 색상 제거

색상으로 출력하는 스크립트가 있어서 ANSI 코드를 삭제해야 합니다.

#!/bin/bash

exec > >(tee log)   # redirect the output to a file but keep it on stdout
exec 2>&1

./somescript

출력은 (로그 파일에) 다음과 같습니다.

java (pid  12321) is running...@[60G[@[0;32m  OK  @[0;39m]

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★@그 자리에.

스크립트를 다음과 같이 변경했습니다.

#!/bin/bash

exec > >(tee log)   # redirect the output to a file but keep it on stdout
exec 2>&1

./somescript | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"

그러나 이제 로그 파일에 다음 정보가 표시됩니다.

java (pid  12321) is running...@[60G[  OK  ]

하면 이 이러다'를할 수 요?@[60G

스크립트 전체에서 컬러링을 완전히 비활성화하는 방법이 있을까요?

위키피디아에 따르면[m|K] sed는, 「이러다」, 「이러다」를 되어 있습니다.m및 (color 「color」)K('행의 일부').^[[60G에 모든 , 「OK」, 「OK」, 「OK」, 「OK」를 sed선이 커버되지 않는다.

(적절)[m|K]아마 그럴 것이다(m|K) ★★★★★★★★★★★★★★★★★」[mK]파이프 문자를 맞추려고 하지 않기 때문입니다.「 」를 참조해 주세요).

를 「」로 .[mGK] ★★★★★★★★★★★★★★★★★」(m|G|K)을 사용하다

./somescript | sed -r "s/\x1B\[([0-9]{1,3}(;[0-9]{1,2};?)?)?[mGK]//g"

IMHO, 이 답변의 대부분은 이스케이프 코드 안에 있는 것을 제한하려고 합니다. 결과,은 '비슷하다'와 같은 됩니다.[38;5;60m(256-color ANSI 60).

, 「」도 합니다.-r옵션을 지정하여 GNU 확장을 활성화합니다.이것들은 필수는 아니고, 정규식을 읽기 좋게 할 뿐입니다.

하고 GNU가 아닌 256색 이스케이프를 사용하는 입니다.sed:

./somescript | sed 's/\x1B\[[0-9;]\{1,\}[A-Za-z]//g'

하면 '어느 이든'으로 하는 것이 다.[에는 임의의 수의 십진수 및 세미콜론이 있으며 끝은 문자로 끝나 있습니다.이것은 일반적인 ANSI 이스케이프 시퀀스를 모두 포착합니다.

기능에는 생각할 수 있는 모든 ANSI 이스케이프 시퀀스에 대해 보다 크고 일반적인(단, 최소한의 테스트 완료) 솔루션이 있습니다.

./somescript | sed 's/\x1B[@A-Z\\\]^_]\|\x1B\[[0-9:;<=>?]*[-!"#$%&'"'"'()*+,.\/]*[][\\@A-Z^_`a-z{|}~]//g'

문제가 있는 (@edi9999) SI를 합니다. | sed "s/\x0f//g"마지막까지, 이것은 모든 제어 문자에 대해 기능합니다.0f16진수)와

알게 되었다ansi2txtcolorized-logsSTDIN에서 를 드롭합니다.STDIN에서ANSI 제어 코드를 드롭합니다.

사용 예:

./somescript | ansi2txt

소스 코드 http://github.com/kilobyte/colorized-logs

다른 답변에서는 제대로 된 결과를 얻을 수 없었지만 다음 답변이 도움이 되었습니다.

somescript | sed -r "s/[[:cntrl:]]\[[0-9]{1,3}m//g"

컨트롤 문자 "^["만 제거하면 나머지 색상 데이터(예: "33m")가 남습니다.색깔 코드와 "m"을 포함하면 효과가 있었어.s/\x1B//g가 작동하지 않는 것은 \x1B[31m은 확실히 에코와 연동하기 때문입니다.

Mac OSX 또는 BSD용

./somescript | sed $'s,\x1b\\[[0-9;]*[a-zA-Z],,g'

다음 정규 표현에서는 ANSI 이스케이프 코드 시퀀스와 3자리 색상이 누락됩니다.예시수정을 regex101.com에서 참조하십시오.

대신 이것을 사용하세요.

./somescript | sed -r 's/\x1B\[(;?[0-9]{1,3})+[mGK]//g'

저도 가끔 SI 캐릭터가 나오는 문제가 있었어요.

이런 .echo "$(tput setaf 1)foo$(tput sgr0) bar"

다음은 SI 문자(Shift In)(0x0f)도 삭제하는 방법입니다.

./somescript | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g" | sed "s/\x0f//g"

텍스트 스트림에서 일반적인 ANSI 코드를 필터링하는 순수 Bash 기능:

# Strips common ANSI codes from a text stream

shopt -s extglob # Enable Bash Extended Globbing expressions
ansi_filter() {
  local line
  local IFS=
  while read -r line || [[ "$line" ]]; do
    printf '%s\n' "${line//$'\e'[\[(]*([0-9;])[@-n]/}"
  done
}

참조:

  1. linuxjournal.com: 확장글로빙
  2. gnu.org: Bash 파라미터 확장

저도 비슷한 문제가 있었어요. 모든 코드에 잘 했지만, 에 의해 ."$(tput sgr0)"(일부러)

예를 들어, 다음 예에서 davemyron에 의한 코멘트 솔루션의 결과 문자열 길이는 6이 아니라 9입니다.

#!/usr/bin/env bash

string="$(tput setaf 9)foobar$(tput sgr0)"
string_sed="$( sed -r "s/\x1B\[[0-9;]*[JKmsu]//g" <<< "${string}" )"
echo ${#string_sed}

regex를 하여 regex가 된 순서와 일치하도록 .sgr0\E(B

string_sed="$( sed -r "s/\x1B(\[[0-9;]*[JKmsu]|\(B)//g" <<< "${string}" )"

잘 모르겠다../somescript, 되어 있지 않은 하여 이스케이프 시퀀스를 할 수 .

TERM=dumb ./somescript 

예를 들면,

TERM=dumb tput sgr0 | xxd

출력되지 않는 것을 알 수 있습니다.

tput sgr0 | xxd
00000000: 1b28 421b 5b6d                           .(B.[m

(xterm-256color의 경우).

ANSI 이스케이프 시퀀스를 처리하는 전용 도구도 있습니다. 앤시필터입니다.디폴트 사용--text출력 포맷을 사용하여 모든 ANSI 이스케이프 시퀀스를 삭제합니다(주: 컬러링뿐만이 아닙니다).

참조: https://stackoverflow.com/a/6534712

여기 순수한 Bash 해결책이 있습니다.

로 저장하다strip-escape-codes.sh한 파일을 만든 실행하다.<command-producing-colorful-output> | ./strip-escape-codes.sh.

이것에 의해, 모든 ANSI 이스케이프 코드/시퀀스가 삭제됩니다.색상만 제거하려는 경우 바꾸기[a-zA-Z]"m".

Bash > = 4.0:

#!/usr/bin/env bash

# Strip ANSI escape codes/sequences [$1: input string, $2: target variable]
function strip_escape_codes() {
    local _input="$1" _i _char _escape=0
    local -n _output="$2"; _output=""
    for (( _i=0; _i < ${#_input}; _i++ )); do
        _char="${_input:_i:1}"
        if (( ${_escape} == 1 )); then
            if [[ "${_char}" == [a-zA-Z] ]]; then
                _escape=0
            fi
            continue
        fi
        if [[ "${_char}" == $'\e' ]]; then
            _escape=1
            continue
        fi
        _output+="${_char}"
    done
}

while read -r line; do
    strip_escape_codes "${line}" line_stripped
    echo "${line_stripped}"
done

Bash < 4.0:

#!/usr/bin/env bash

# Strip ANSI escape codes/sequences [$1: input string, $2: target variable]
function strip_escape_codes() {
    local input="${1//\"/\\\"}" output="" i char escape=0
    for (( i=0; i < ${#input}; ++i )); do         # process all characters of input string
        char="${input:i:1}"                       # get current character from input string
        if (( ${escape} == 1 )); then             # if we're currently within an escape sequence, check if
            if [[ "${char}" == [a-zA-Z] ]]; then  # end is reached, i.e. if current character is a letter
                escape=0                          # end reached, we're no longer within an escape sequence
            fi
            continue                              # skip current character, i.e. do not add to ouput
        fi
        if [[ "${char}" == $'\e' ]]; then         # if current character is '\e', we've reached the start
            escape=1                              # of an escape sequence -> set flag
            continue                              # skip current character, i.e. do not add to ouput
        fi
        output+="${char}"                         # add current character to output
    done
    eval "$2=\"${output}\""                       # assign output to target variable
}

while read -r line; do
    strip_escape_codes "${line}" line_stripped
    echo "${line_stripped}"
done

@jeff-bowman의 솔루션은 색상 코드를 없애는 데 도움이 되었습니다.조금 더 제거하기 위해 regex에 작은 부분을 추가했습니다.

sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g" # Original. Removed Red ([31;40m[1m[error][0m)
sed -r "s/\x1B\[([0-9];)?([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g" # With an addition, removed yellow and green ([1;33;40m[1m[warning][0m and [1;32;40m[1m[ok][0m)
                ^^^^^^^^^
                remove Yellow and Green (and maybe more colors)

음, 이 방법이 도움이 될지는 모르겠지만 'tr'는 제어 코드를 '스트립'(삭제)합니다. 시도해 보십시오.

./somescript | tr -d '[:cntrl:]'

논란의 여지가 있는 아이디어는 이 프로세스 환경의 단말기 설정을 재구성하여 단말기가 색상을 지원하지 않음을 프로세스에 알리는 것입니다.

TERM=xterm-mono ./somescript색상 설정을 .사용자 고유의 OS 및 스크립트의 터미널 색상 설정을 이해하는 기능을 갖춘 YMMV.

다른 솔루션에서는 정상적으로 처리되지 않는 컬러화된 출력에 문제가 있어 이 perl을 한 라이너로 만들었습니다. 곳을 \e bracket " " " " " " "\[가 붙습니다.\d+하여 "로 ",m.

perl -ple 's/\e\[\d+(;\d+)*m//g'

컬러화된 컴파일러 출력에 매우 적합한 것 같습니다.

다른 답변은 모든 탈출 코드를 제거하지 못했습니다(예:\x1b[?25l를 참조해 주세요.

이 작은 sed 명령으로 효과를 볼 수 있습니다.

./somescript | sed -r 's/[\x1B\x9B][][()#;?]*(([a-zA-Z0-9;]*\x07)|([0-9;]*[0-9A-PRZcf-ntqry=><~]))//g'

regex는 https://github.com/acarl005/stripansi/blob/master/stripansi.go#L7를 수정한 것입니다.

OP와 비슷한 일을 하려다 우연히 이 질문/답변을 접하게 되었습니다.저는 다른 유용한 자료를 찾아 이를 바탕으로 로그 스크립트를 작성했습니다.다른 사람에게 도움이 될까봐 여기에 글을 올린다.

링크를 자세히 살펴보면 리다이렉션을 이해하는 데 도움이 됩니다.이러한 방향 변경은 저도 이제 막 이해하기 시작했기 때문에 설명하지 않겠습니다.

사용법을 사용하면 컬러화된 출력이 콘솔에 렌더링되고 로그 파일로 전송되는 텍스트에서 컬러 코드가 제거됩니다.또, 동작하지 않는 커맨드에 대해서는, 로그 파일에 stderr 가 포함됩니다.

편집: 하단에 더 많은 사용법을 추가하여 다양한 방법으로 로그인하는 방법을 보여줍니다.

#!/bin/bash
set -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

. $DIR/dev.conf
. $DIR/colors.cfg

filename=$(basename ${BASH_SOURCE[0]})
# remove extension
# filename=`echo $filename | grep -oP '.*?(?=\.)'`
filename=`echo $filename | awk -F\. '{print $1}'`
log=$DIR/logs/$filename-$target

if [ -f $log ]; then
  cp $log "$log.bak"
fi

exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>$log 2>&1


# log message
log(){
    local m="$@"
    echo -e "*** ${m} ***" >&3
    echo "=================================================================================" >&3
  local r="$@"
    echo "================================================================================="
    echo -e "*** $r ***" | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g"
    echo "================================================================================="
}

echo "=================================================================================" >&3
log "${Cyan}The ${Yellow}${COMPOSE_PROJECT_NAME} ${filename} ${Cyan}script has been executed${NC}"
log $(ls) #log $(<command>)

log "${Green}Apply tag to image $source with version $version${NC}"
# log $(exec docker tag $source $target 3>&2) #prints error only to console
# log $(docker tag $source $target 2>&1) #prints error to both but doesn't exit on fail
log $(docker tag $source $target 2>&1) && exit $? #prints error to both AND exits on fail
# docker tag $source $target 2>&1 | tee $log # prints gibberish to log
echo $? # prints 0 because log function was successful
log "${Purple}Push $target to acr${NC}"


다음은 도움이 된 기타 링크입니다.

많은 파일에서 자주 해야 하기 때문에 perl을 사용했습니다.그러면 filename*.txt의 모든 파일이 처리되고 포맷이 삭제됩니다.이것은 나의 사용 예에 유효하고, 다른 사람에게도 도움이 될 수 있으므로, 여기에 투고하는 것을 생각해 주세요.파일명을 filename*.txt 대신에 치환하거나, 아래의 파일명을 공백으로 구분해 설정할 수 있습니다.

$ FILENAME=$(ls filename*.txt) ; for file in $(echo $FILENAME); do echo $file; cat $file | perl -pe 's/\e([^\[\]]|\[.*?[a-zA-Z]|\].*?\a)//g' | col -b > $file-new; mv $file-new $file; done

나의 공헌:

./somescript | sed -r "s/\\x1B[\\x5d\[]([0-9]{1,3}(;[0-9]{1,3})?(;[0-9]{1,3})?)?[mGK]?//g"

MacOS용

$ my_program | pbcopy && pbpaste

이것으로 충분합니다.

./somescript | cat

언급URL : https://stackoverflow.com/questions/17998978/removing-colors-from-output