如何在Bash中将字符串转换为其他字符串?

时间:2018-07-22 19:12:07

标签: linux bash unix scripting

我在此行中有这些预先声明的字符串:

echo "You are have '$ID' as '$TYP' with '$PRI'."

但是,$TYP变量的形式很简短,我希望将其转换为可读性更好的形式,具体来说:

INC -> Include
PRO -> Proactive

因此,当$TYPINC时,将输出:

You are have 'something' as 'Include' with 'something else'.

我该怎么做?我将不胜感激。

2 个答案:

答案 0 :(得分:1)

听起来 就像您只想在Include$TYP时输出INC,而在Proactive时输出PRO可以像这样简单:

if   [[ "$TYP" = "INC" ]] ; then
    LongType="Include"
elif [[ "$TYP" = "PRO" ]] ; then
    LongType="Proactive"
else
    LongType="unknown"
fi
echo "You are have '${ID}' as '${LongType}' with '${PRI}'."

但是,为了简洁明了的代码,您还可以使用关联数组来实现它,如下所示:

# Create lookup table, done *once* at start up.

declare -A Lookup
Lookup=([INC]=Incoming [PRO]=Proactive)

# Lookup item whenever you want.

echo "You are have '${ID}' as '${Lookup[${TYP}]:=unknown}' with '${PRI}'."

${Lookup[${TYP}]:=unknown}是这里的魔力。 ${Lookup[${TYP}]}位会在关联数组中查找$TYP键,并返回值;如果没有该值的键,则返回一个空字符串。

:=unknown位用文字unknown替换了一个空字符串。

后一种解决方案产生的代码可能比您必须创建的代码少得多,尤其是如果您扩展了可能性的话。

答案 1 :(得分:0)

好的,我知道了。谢谢@那个家伙。我不知道为什么我完全跳过了这个逻辑。我只是在让它变得比原来更难...

if [[ $TYP == "INC" ]]
then
   echo "foo"
elif [[ $TYP == "PRO" ]]
then
   echo "bar"
fi