![]() |
Passing variables which contain special characters to sed
I've got a for loop like the following:
Code:
for i in "textA" "textB" "text/C"; do sed -n "/${i}/,/^$\|pattern/p" targetfile; doneThe problem is, it chokes on the "text/C" because it contains a forward slash, and returns an error message similar to the following: sed -e expression 31, char 14: unknown command: `C' Any suggestions on how to handle special characters in this instance? Thanks. |
You can often escape special characters with a backslash. Have you tried:
Code:
text\/C |
The problem is, this list will vary each time I run the loop. The actual list I'm using contains upwards of 150 items, and the number of items containing special characters varies. I need a way to escape special characters no matter what is passed to the variable.
Thanks. |
Will it always be preceded by "text"? If so escaping the character after "text" might work - \B would likely still see the character as B and \/C would make it see it as /C.
|
You might need to look at sanitizing each variable for unusual characters and escaping them prior to use in your sed.
|
In Bash, to escape characters special to standard sed patterns, you could try something like the following within the loop:
Code:
# start with the original pattern |
The easiest way is simply to change the delimiter that sed uses.
(Edit: the easiest way to avoid conflicting with the delimiter at least. For regex characters, you'd have to do variable sanitizing as above.) For the 's' substitution command, just replace the slash with another ascii character. Simply choose something that won't ever be found in the expression itself. You can do the same thing for the target range brackets, except that the first instance needs to be prefixed with a backslash. To use the underscore as the delimiter, for example (spaced out a bit for better readability): Code:
for i in "textA" "textB" "text/C"; doCode:
|
Thanks David the H., that's the solution!
I was trying to change the delimiter previously, but I didn't have the syntax correct, so I was getting an error. When I use : as the delimiter in the format you listed above, it's working! Thanks to everyone else who offered input as well! |
| All times are GMT -5. The time now is 11:11 AM. |