vinod
vinod

Reputation: 87

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

Upvotes: 1

Views: 377

Answers (2)

Мона_Сах
Мона_Сах

Reputation: 322

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.

Upvotes: 1

Zang MingJie
Zang MingJie

Reputation: 5275

The special characters is stored correct in the variable grepresult, it is echo who convert \t to TAB

try:

echo -E $grepresult

where -E prevent echo from doing backslash escapes

Upvotes: 0

Related Questions