在终端上使用jq打印带颜色的原始输出

3
我试图在终端上打印一份报告。该报告是JSON格式的,我将其作为原始jq输出打印在终端上。
我尝试为一些值着色,类似于这样的行:
echo -e "\033[31m Hello World"

但是一直无法做到。

当我像下面这样做时

echo '[{"value": "New", "onclick": "Ready"},{"value": "Old", "onclick": "Stopped"}]' | jq -r  '.[] | "\n", .value, .onclick '

它会打印如下内容:

新 (New)

就绪 (Ready)

旧 (Old)

停止 (Stopped)

所以它理解换行符 \n,但我想要像这样的格式:

新 (红色加粗字体)

就绪 (Ready)

旧 (红色加粗字体)

停止 (Stopped)

以使其更易读。

1个回答

8
这个插图足以帮助你跨过难关:
jq -n -r '

def colors:
 {
 "black": "\u001b[30m",
 "red": "\u001b[31m",
 "green": "\u001b[32m",
 "yellow": "\u001b[33m",
 "blue": "\u001b[34m",
 "magenta": "\u001b[35m",
 "cyan": "\u001b[36m",
 "white": "\u001b[37m",
 "reset": "\u001b[0m",
};

colors.red + "red" + colors.green + "green"
'

详解

# print $text in the specified color
def pc($text; color):
  (colors | color) + $text + colors.reset;

# Usage example:
pc("red"; .red) + pc("green"; .green)

感谢@peak的帮助。我能够形成我的最终表达式。` jq --raw-output 'def red: "\u001b[31m"; def yellow: "\u001b[33m"; def reset: "\u001b[0m"; .requestObj[] | select(. != null) | "\n", red + .category + reset, yellow + .messages[] + reset' 将reset添加为最佳实践。 ` - ankitj
-r did the trick, thank you! jq -r '.logs[].message' < my.json - akostadinov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接