jennifer
jennifer

Reputation:

Perl Regular Expressions + delete line if it starts with #

How to delete lines if they begin with a "#" character using Perl regular expressions?

For example (need to delete the following examples)

line="#a"
line="     #a"
line="# a"
line="    # a"

...

the required syntax

   $line =~ s/......../..

or skip loop if line begins with "#"

from my code:

open my $IN  ,'<', $file      or die "can't open '$file'  for reading: $!";
while( defined( $line = <$IN> ) ){

.
.
.

Upvotes: 3

Views: 37560

Answers (4)

Montclair
Montclair

Reputation: 91

$text ~= /^\s*#.*\n//g

That will delete all of the lines with # in the entire file of $text, without requiring that you loop through each line of the text manually.

Upvotes: 0

Amozoss
Amozoss

Reputation: 1445

Based off Aristotle Pagaltzis's answer you could do:

perl -ni.bak -e'print unless m/^\s*#/' deletelines.txt

Here, the -n switch makes perl put a loop around the code you provide which will read all the files you pass on the command line in sequence. The -i switch (for “in-place”) says to collect the output from your script and overwrite the original contents of each file with it. The .bak parameter to the -i option tells perl to keep a backup of the original file in a file named after the original file name with .bak appended. For all of these bits, see perldoc perlrun.

deletelines.txt (initially):

#a
b
     #a 
#   a
  c
         # a

becomes:

b
  c

Upvotes: 7

grawity_u1686
grawity_u1686

Reputation: 16282

You don't delete lines with s///. (In a loop, you probably want next;)

In the snippet you posted, it would be:

while (my $line = <IN>) {
    if ($line =~ /^\s*#/) { next; }
    # will skip the rest of the code if a line matches

    ...
}

Shorter forms /^\s*#/ and next; and next if /^\s*#/; are possible.


perldoc perlre

/^\s*#/
  • ^ - "the beginning of the line"
  • \s - "a whitespace character"
  • * - "0 or more times"
  • # - just a #

Upvotes: 13

RedGrittyBrick
RedGrittyBrick

Reputation: 4002

Program (Cut & paste whole thing including DATA section, adjust shebang line, run)

#!/usr/bin/perl
use strict;
use warnings;

while(<DATA>) {
  next if /^\s*#/;  # skip comments
  print;            # process data
}

__DATA__
# comment
data
  # another comment
more data

Output

data
more data

Upvotes: 2

Related Questions