Search code examples
linuxcomments

remove lines/contents that matches a pattern in Linux


I want to remove all lines and contents in comments i.e. "--" from a file. For example my data is

---------
--Text1
--Text2
---------
Text3 --Text4
Text5

and my output should be

Text3
Text5

I tried sed '/^--/d' test.txt and it removed all lines that starts with -- but I want to remove all contents after -- as well like line 5 above.


Solution

  • Use this Perl one-liner:

    $ echo 'foo--bar' | perl -pe 's/--.*//' 
    foo
    

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

    s/--.*// : Replace literal -- followed by any character repeated 0 or more times with nothing (= delete comments).

    SEE ALSO:
    perldoc perlrun: how to execute the Perl interpreter: command line switches
    perldoc perlre: Perl regular expressions (regexes)
    perldoc perlre: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups