How do you insert chars with sed when the char itself is '\'...
I have a string of a C dump and I would like to replace the 'x' with '\x'
using sed. However, sed seems to have trouble with the '\' char Here's the string, a lot longer than this x83x23x42x23x85x24 I've been trying this Code:
sed -i 's/x/\x/g' file.txt |
Use 3 (yep 3) backslashes
|
Ummmmm......would you believe TWO backslashes?
the backslash (\) is used to "escape" something--most often to change meaning from special to ordinary, but it can be the other way too. In this case, there is no special character and nothing to escape, so "\" does nothing. In you example, I'm betting that it simply replaced every "x" with "x"....;) Some examples (in regexes such as used in the sed "s" command): . any character \. literal period $a value of variable "a" \$a literal "\$a" \ often means nothing \x same as "x" \\ literal "\" \\\. literal "\", followed by a literal "\." In other words "\\\." means literal "\." If you're not confused yet, we can try harder....;) Finally, don't use sed -i until you are sure your code is working. It changes the file in place. You are always safer doing: sed '<<stuff>>" oldfile > newfile |
@trist007
This code will give you the results you want. Code:
sed 's/x/\\x/g' file.txt \x83\x23\x42\x23\x85\x24 If you like the results, send the output to another file. sed 's/x/\\x/g' file.txt > newfile |
Ahhh - sed and it's quotes again.
Sorry, didn't notice the OP was using single quotes. |
Quote:
One \ tries to escape something in the shell Two \\tries to escape something in the shell AND in sed. Three \\\ just makes it literal So---if there is nothing to escape in the shell, why can't it just pass the \ thru? My head hurts...... |
The code I gave to trist007 does work. I replicated his/her situation from the shell. Try it and see.
echo x83x23x42x23x85x24 | sed 's/x/\\x/g' I've used one backslash for escaping because I remembered anytime you wish to pass a literal character to the shell always precede it with a \ I agree sed and awk have the most confusing and complex arrangements to comprehend. :) But, powerful indeed... |
What if I need to insert forward slashes '/'
for example Code:
sed -i 's/^/wget http://www.example.net//g' test.txt I want to add the string "wget http://www.example.net/" at the beginning of every line in the test.txt file. |
Code:
sed 's/^/wget http\:\/\/www.example.net\/ /g' test.txt This is how. Anytime, you want a character to be literal and not a shell function, just precede it with a back slash \ If you are happy with the results, just redirect the output to a new file. sed 's/^/wget http\:\/\/www.example.net\/ /g' test.txt > some_file |
All times are GMT -5. The time now is 06:56 AM. |