我有一个变量var
。想要打印Code:
in之后的行blue
(但删除指定的行Code:
),而其余的则打印在 中green
。我使用一个 bash 脚本调用 awk 来执行运行 ubuntu 的变量处理。
sgr="$( tput sgr0 )"
grn="$( tput bold; tput setaf 34 )"
blu="$( tput bold; tput setaf 39 )"
var="
Description
Code:
for i in {1..72..1}; do shft+=\" \"; done
Details"
printf '%s\n' "$var" \
| awk -v kb="$blu" -v kg="$grn" -v rst="$sgr" \
'{ codefound = 0
fm="%s%s%s\n"
if (codefound) { printf(fm, kb, $0, rst) }
else { printf(fm, kg, $0, rst) }
}'
如何定义颜色本身awk
?
我想生成以下内容(# 用于描述文本的前景色):
Description # green
for i in {1..72..1}; do shft+=" "; done # blue
Details # green
答案1
很大程度上基于答案使用 awk 为 bash 中的输出着色,这可能是您想要的这种情况以及您需要更改(可能是多种)前景色和/或背景颜色的任何类似情况:
$ cat tst.awk
BEGIN {
split("BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE",tputColors)
for (i in tputColors) {
colorName = tputColors[i]
colorNr = i-1
cmd = "tput setaf " colorNr
fgEscSeq[colorName] = ( (cmd | getline escSeq) > 0 ? escSeq : "<" colorName ">" )
close(cmd)
cmd = "tput setab " colorNr
bgEscSeq[colorName] = ( (cmd | getline escSeq) > 0 ? escSeq : "<" colorName ">" )
close(cmd)
}
cmd = "tput sgr0"
colorOff = ( (cmd | getline escSeq) > 0 ? escSeq : "<sgr0>" )
close(cmd)
fgColor = dfltFgColor = "GREEN"
}
/Code:/ { fgColor = "BLUE"; next }
!NF { fgColor = dfltFgColor }
{ print fgEscSeq[fgColor] $0 colorOff }
如果您不想使用tput
来定义颜色,请参阅通过 awk 或其他方法搜索和着色线了解如何使用转义序列。
答案2
要在 awk 中使用 ANSI 转义码对行进行着色,例如包含字符串“WORD”的行,您可以执行以下操作:
printf '%s\n' "$var" |
awk '
BEGIN{
blue ="\033[1;44m"
rst ="\033[0m"
}
/WORD/{ $0=blue $0 rst }1'
满足您需要的代码是:
printf '%s\n' "$var" |
awk '
BEGIN{
green ="\033[1;42m" #default output color
blue ="\033[1;44m"
rst ="\033[0m"
}
/Code:$/ { Clr=1; next } # active the blue colored ouptut
/Details$/{ Clr=0 } # disable the blue colored output
{ print (Clr? blue : green) $0 rst }'
答案3
我不会awk
为此使用,我只会使用sed
and printf
:
#!/bin/bash
var="
Description
Code:
for i in {1..72..1}; do shft+=' '; done
Details"
sgr="$( tput sgr0 )"
grn="$( tput bold; tput setaf 34 )"
blu="$( tput bold; tput setaf 39 )"
printf "%s" "$grn"; sed -E "s/Code:/$blu/; s/^( *Details.*)/${grn}\1${sgr}/" <<<"$var";
这会产生:
如果你坚持awk
,这样的事情会起作用:
#!/bin/bash
var="
Description
Code:
for i in {1..72..1}; do shft+=' '; done
Details"
sgr="$( tput sgr0 )"
grn="$( tput bold; tput setaf 34 )"
blu="$( tput bold; tput setaf 39 )"
awk -v sgr="$( tput sgr0 )" \
-v grn="$( tput bold; tput setaf 34 )" \
-v blu="$( tput bold; tput setaf 39 )" \
'BEGIN{ printf "%s", grn }
{
if(/Code:/){ printf "%s", blu }
else if(/Details/){ printf "%s%s%s\n",grn, $0, sgr }
else { print }
}' <<<"$var";