How to use sed to examine the line without specific content?
2014-07
I made a toy file named toy, its content is like:
aaa
bbb
My first idea is to use:
sed -n '/[^a]/ p' toy
bbb
it prints out bbb, but when I added
bb ab
to the end of toy file. I found it lose its power
sed -n '/[^a]/ p' toy
bbb
bb ab
How should I scan the whole line with the pattern?
by using
sed '/a\+/d' toy
you can print out any line without any 'a' in the file.
I'm using CMD on Windows Xp to replace special text with Sed. I'm using this command for replace special characters like $ or *
:
sed -i "s/\*/123/g;" 1.txt
But how command must i use to replace this strings with ciao!
in my text files? Is possible?
\\
\\\
""
sed.exe -i "s/{\*)(//123/
sed -i "s/\\/123/g;" 1.txt
the previous command does not work because i have \
, "
and other special strings that sed use to make regex.
Looking for literal strings with a regular expression, when the search-string contains special characters, is sometimes not as simple as looking for patterns, but you can do it with a bit of juggling.
Note: The echo
command must cater for CMD-special-characters, so it needs ^^
to escape a single ^
and ^|
to escape |
... You don't need CMD's escape-character ^
if you type directly into the file.
Step 1: Create a file, named literal-srch-strings.txt, which containing the exact (unaltered) string to be replaced. There are 2 ways to create this file:
As a command issued at CMD's commandline, or as a command in a .cmd/.bat command-script.
echo sed -i^^/\\*$/$[{" ;"> literal-srch-strings.txt
Make literal-srch-strings.txt yourself, in your text editor.
In this case, you should not use the CMD-escape-character^
, so the line is has just one^
, not^^
-- This is because you are bypassing the CMD-shell.
Here is what is needed in the .txt file (just as the filename says :)sed -i^/\\*$/$[{" ;"
Step 2: Make a sed script, named str-to-regex.sed , to convert the string(s) into sed regex(s).
Note that the same issue of the CMD-escape-character ^
applies to this step, so again, there are 2 ways you can create the .sed file:
As a command:
echo s/[]\/$*.^^^|[]/\\^&/g; s/.*/s\/^&\/Ciao!\/g/> str-to-regex.sed
Using your text editor, make a file named str-to-regex.sed, containing:
s/[]\/$*.^|[]/\\&/g; s/.*/s\/&\/Ciao!\/g/
Step 3: Run the sed-script which converts the string into a sed regeular expression, and
send its output to another sed-script, replace-text.sed, which will make the actual replacement.
sed -f str-to-regex.sed literal-srch-strings.txt > replace-text.sed
Step 4: Run replace-text.sed -- For the test we can use literal-srch-strings.txt as the input file, but you can, of course, use any input file.
sed -f replace-text.sed literal-srch-strings.txt
Here is the output:
Ciao!
To override the meaning of special characters on the command-line (or lines in a batch file), escape them with the ^ (carat) character. To enter a literal carat character, use two of them in a row.