Search code examples
bashsedspecial-characters

How to pass special characters through sed


I want to pass this command in my script:
sed -n -e "/Next</a></p>/,/Next</a></p>/ p" file.txt
This command (should) extract all text between the two matched patterns, which are both Next</a></p> in my case. However when I run my script I keep getting errors. I've tried:
sed -n -e "/Next\<\/a\>\<\/p\>/,/Next<\/a\>\<\/p>/ p" file.txt with no luck.

I believe the generic pattern for this command is this:
sed -n -e "/pattern1/,/pattern2/ p" file.txt
I can't get it working for Next</a></p> though and I'm guessing it has something to do with the special characters I am encasing. Is there any way to pass Next</a></p> in the sed command? Thanks in advance guys! This community is awesome!


Solution

  • You don't need to use / as a regular expression delimiter. Using a different character will make quoting issues slightly easier. The syntax is

    \cregexc

    where c can be any character (other than \) that you don't use in the regex. In this case, : might be a good choice:

    sed -n -e '\:Next</a></p>:,\:Next</a></p>: p' file.txt
    

    Note that I changed " to ' because inside double quotes, \ will be interpreted by bash as an escape character, whereas inside single quotes \ is just treated as a regular character. Consequently, you could have written the version with escaped slashes like this:

    sed -n -e '/Next<\/a><\/p>/,/Next<\/a><\/p>/ p' file.txt
    

    but I think the version with colons is (slightly) easier to read.