vinod vinod - 6 months ago 8
Bash Question

How to get the special characters as a normal string in shell

I have written a shell script which reads a file and take the path of a file required to perform particular task but if the path of the file contains any special characters it is not taking the complete path

for eg the path is \web\take\ab
the value i am getting is \web ake\ab here it is treating \t as tab and printing the tab so how to avoid this

My code is
grepresult=

grep "Cannot " input.txt | cut -f 2,3 -d":"


echo $grepresult

So please help how can I get the special characters into the string

Answer

In POSIX compliant shells,with some exceptions, the interpretation of backslash is by default enabled.

The problem as you know is that, shell interprets \ with its special meaning.To have the backslash in the output, simply backslash it.

Input

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


Script

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

should do the trick. Look for ${var//Pattern/Replacement} in Shell Parameter Substitution.

Output

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

Also good to check Treatment of backslashes across shells.

Comments