如何将特殊字符作为shell中的普通字符串

时间:2016-05-26 07:38:31

标签: shell

我编写了一个shell脚本,它读取文件并获取执行特定任务所需的文件路径,但如果文件路径包含任何特殊字符,则不会采用完整路径

例如路径是\ web \ take \ ab 我得到的值是\ web ake \ ab这里它将\ t作为标签处理并打印标签,以便如何避免这种情况

我的代码是 grepresult = grep "Cannot " input.txt | cut -f 2,3 -d":"

echo $ grepresult

所以请帮助我如何将特殊字符放入字符串

2 个答案:

答案 0 :(得分:1)

在符合POSIX标准的shell中,除了一些例外情况,默认情况下会启用反斜杠的解释。

你知道的问题是,shell以其特殊含义解释\。要在输出中加上反斜杠,只需反斜杠即可。

<强>输入

$ grepresult="sometestt\n\b\a"


<强>脚本

echo  "${grepresult//\\/\\\\}"
#since \ has special meaning here as well, `\\` makes the character `\`

应该做的伎俩。在Shell Parameter Substitution中查找${var//Pattern/Replacement}

<强>输出

$ echo  "${grepresult//\\/\\\\}"
sometestt\n\b\a

检查Treatment of backslashes across shells也很好。

答案 1 :(得分:0)

特殊字符在变量grepresult中正确存储,echo\t转换为TAB

尝试:

echo -E $grepresult

其中-E阻止echo执行反斜杠转义

相关问题