答案1
我通过编写一个简单的 python 脚本用 tmux 颜色变量替换 ANSI 代码解决了这个问题。
#!/usr/local/bin/python
s = raw_input("")
s = s.replace('\x1b[32m', '#[fg=colour10]')
s = s.replace('\x1b[93m', '#[fg=colour11]')
s = s.replace('\x1b[0m', '#[fg=colour255]')
print s
我只是将输出通过管道传输到脚本:istats | grep "CPU temp" | ansi2tmuxcolors.py
答案2
我通过编写一个单独的 shell 来概括 Subliminalmau5 答案
sed -r 's,\x1b\[38;5;([0-9]+)m,#[fg=colour\1],g'|sed -r 's,\x1b\[1m,#[bold],g'|sed -r 's,\x1b\[0m,#[default],g'
它将所有 256 种颜色的 ANSI 转换为 tmux。
答案3
我编写了一个 Perl 脚本来将 ANSI 颜色转义代码转换为 TMUX 颜色转义代码:https://raw.githubusercontent.com/SimonLammer/dotfiles/0a0828b1a7583968a5f8e65f2f31c659562c3ece/data/tmux/scripts/ansi-colors-to-tmux.pl
#!/bin/perl -nw
# This converts ANSI color escape sequences to TMUX color escape sequences,
# which can be used in the status line.
# Example: "\x1b[31mERROR\x1b[0m" -> "#[fg=red,]ERROR#[default,]"
# The following SGR codes are supported:
# - 0
# - 1
# - 30 - 49
# - 90 - 97
# - 100 - 107
use warnings;
use strict;
my @colors = ("black", "red", "green", "yellow", "blue", "magenta", "cyan", "white");
while(/(.*?)(\x1b\[((\d+;?)+)m)/gc) {
print "$1#[";
my @sgr = split /;/, $3;
for(my $i = 0; $i <= $#sgr; $i++) {
if ($sgr[$i] eq "0") {
print "default";
} elsif ($sgr[$i] eq "1") {
print "bright";
} elsif ($sgr[$i] =~ /(3|4|9|10)(\d)/) {
if ($1 eq "3") {
print "fg=";
} elsif ($1 eq "4") {
print "bg=";
} elsif ($1 eq "9") {
print "fg=bright";
} elsif ($1 eq "4") {
print "bg=bright";
}
if ($2 eq "8") { # SGR 38 or 48
$i++;
if ($sgr[$i] eq "5") {
$i++;
print "colour" . $sgr[$i];
} elsif ($sgr[$i] eq "2") {
printf("#%02X%02X%02X", $sgr[$i + 1], $sgr[$i + 2], $sgr[$i + 3]);
$i += 3;
} else {
die "Invalid SGR 38;" . $sgr[$i];
}
} elsif ($2 eq "9") {
print "default";
} else {
print $colors[$2];
}
} else { # Unknown/ignored SGR code
next;
}
print ",";
}
print "]";
}
/\G(.*)/gs;
print "$1";