我需要在字符串中的某些单词周围添加一些自定义语法。举个简单的例子,所有包含“A”或“B”的单词都应单独用“<red>
”和“</red>
”包围,所有包含“H”或“F”的单词都应该被包围“<blue>
”和“</blue>
”等词语被忽略了。请参阅此示例字符串:
THE BEAR ATE THE FISH
此行变为:
<blue>THE</blue> <red>BEAR</red> <red>ATE</red> <blue>THE</blue> <blue>FISH</blue>
AFRICA
”变为“<blue><red>AFRICA</red></blue>
”。如何在包含特定字母的单词周围添加此自定义语法?
答案 0 :(得分:2)
如果允许awk
解决方案:
$ foo="THE BEAR ATE THE FISH AFRICA"
$ echo "${foo}" | awk '{
gsub(/[^[:space:]]*(A|B)[^[:space:]]*/, "<red>&</red>");
gsub(/[^[:space:]]*(H|F)[^[:space:]]*/, "<blue>&</blue>")
}1'
<blue>THE</blue> <red>BEAR</red> <red>ATE</red> <blue>THE</blue> <blue>FISH</blue> <blue><red>AFRICA</red></blue>
这将保留空格并在{2}匹配的情况下执行<blue><red></red></blue>
。如果两者都不是要求,请转到shell解决方案。
答案 1 :(得分:1)
(也适用于bash)
#!/bin/sh
x='THE BEAR ATE THE FISH IN AFRICA'
for i in $x; do
case $i in
*A*|*B*)
case $i in
*H*|*F*)
printf "<blue><red>$i</red></blue>"
;;
*)
printf "<red>$i</red>"
;;
esac
;;
*H*|*F*)
printf "<blue>$i</blue>"
;;
esac
done
<blue>THE</blue><red>BEAR</red><red>ATE</red><blue>THE</blue><blue>FISH</blue>
<blue><red>AFRICA</red></blue>