user1011471
user1011471

Reputation: 1130

using sed to delete lines containing slashes /

I know in some circumstances, other characters besides / can be used in a sed expression:

sed -e 's.//..g' file replaces // with the empty string in file since we're using . as the separator.

But what if you want to delete lines matching //comment in file?

sed -e './/comment.d' file returns

sed: -e expression #1, char 1: unknown command: `.'

Upvotes: 4

Views: 7279

Answers (2)

Timur Shtatland
Timur Shtatland

Reputation: 12347

To delete lines with comments, select from these Perl one-liners below. They all use m{} form of regex delimiters instead of the more commonly used //. This way, you do not have to escape slashes like so: \/, which makes a double slash look less readable: /\/\//.

Create an example input file:

echo > in_file \
'no comment
// starts with comment
   // starts with whitespace, then has comment
foo // comment is anywhere in the line'

Remove the lines that start start with comment:

perl -ne 'print unless m{^//}' in_file > out_file

Output:

no comment
   // starts with whitespace, then has comment
foo // comment is anywhere in the line

Remove the lines that start with optional whitespace, followed by comment:

perl -ne 'print unless m{^\s*//}' in_file > out_file

Output:

no comment
foo // comment is anywhere in the line

Remove the lines that have a comment anywhere:

perl -ne 'print unless m{//}' in_file > out_file

Output:

no comment

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc perlre: Perl regular expressions (regexes)
perldoc perlrequick: Perl regular expressions quick start

Upvotes: 0

anubhava
anubhava

Reputation: 785098

You can use still use alternate delimiter:

sed '\~//~d' file

Just escape the start of delimeter once.

Upvotes: 13

Related Questions