2017-05-16 26 views
0

我有以下代碼:輸出的桑達着色工作不正常

#!/bin/bash 

reset=$(tput sgr0) 
bold=$(tput bold) 

red=$(tput setaf 1) 
white=$(tput setaf 7) 

pattern[0]='[0-9]' 
replacement[0]="${white}${bold}&${reset}" 

pattern[1]='[a-z]' 
replacement[1]="${red}${bold}&${reset}" 

args=() 
for ((i=0; i < ${#pattern[@]}; i++)) ; do 
    args+=(-e "s/${pattern[i]}/${replacement[i]}/g") 
done 

echo "asdf1234" | sed "${args[@]}" 

它輸出:添加

asdfmm1mmm2mmm3mmm4m 

即額外m字符,所有的字符都是紅色的,數字是不突出顯示。

我的願望是用紅色字母和白色數字。我怎樣才能做到這一點?

回答

1

嘗試這樣的:

#!/bin/bash 

reset=$(tput sgr0)  # \001 
bold=$(tput bold)  # \002 

red=$(tput setaf 1) # \003 
white=$(tput setaf 7) # \004 

pattern[0]='[0-9]' 
replacement[0]=$'\004\002&\001' 

pattern[1]='[a-z]' 
replacement[1]=$'\003\002&\001' 

args=() 
for ((i=0; i < ${#pattern[@]}; i++)) ; do 
    args+=(-e "s/${pattern[i]}/${replacement[i]}/g") 
done 

echo "asdf1234" | sed "${args[@]}" \ 
    | sed -e $'s/\001/'$reset'/g' \ 
      -e $'s/\002/'$bold'/g' \ 
      -e $'s/\003/'$red'/g' \ 
      -e $'s/\004/'$white'/g' 

輸出我的系統上:

screenshot

+0

如果輸入包含\ 001等,可能會中斷。 – choroba

+0

謝謝。這工作。但是'00x'代碼使得代碼不可讀。我願意使用變量名來保持它的可讀性。你能告訴我該怎麼做嗎? – george

+0

然後只是把'\ ooo'分配給變數。例如:'_red = $'\ 003'' – pynexj

1

它不起作用的原因是白色和粗體代碼包含由第二個模式匹配的字符。 sed在每個輸入行上順序應用所有圖案,例如

echo a | sed -e s/a/b/ -e s/b/c/ # Outputs "c". 

你需要的是根據捕獲的數據使用具有不同替換的單個表達式,這是可能的。在Perl:

#! /usr/bin/perl 
use warnings; 
use strict; 
use feature qw{ say }; 

use List::Util qw{ first }; 
use Term::ANSIColor qw{ color }; 


my $reset = color('reset'); 
my $bold = color('bold'); 
my $red = color('red'); 
my $white = color('white'); 

my (@pattern, @replacement); 

push @pattern, '[0-9]'; 
push @replacement, "$white$bold"; 

push @pattern, '[a-z]'; 
push @replacement, "$red$bold"; 

my $regex = join '|', map "($_)", @pattern; 

my $string = 'asdf1234'; 

$string =~ s/$regex/ 
    my $i = first { defined $+[$_] } 1 .. $#+; 
    $replacement[$i-1] . "$+$reset" 
    /ge; 

say $string; 

只需更改最後一部分成

while (my $string = <>) { 
    $string =~ s/$regex/ 
     my $i = first { defined $+[$_] } 1 .. $#+; 
     $replacement[$i-1] . "$+$reset" 
     /ge; 

    print $string; 
} 

,使其工藝標準輸入或作爲參數給出的文件。

+0

那麼如何使它工作嗎? – george

+0

Perl來拯救! – choroba

+0

問題是爲bash。 – george