Using Raku (formerly known as Perl_6)
raku -ne '.put if .grep( !/^ [ 1 | 2 ] \s / | / foo | bar / );'
OR
raku -ne '.put if .grep( { !/^ [ 1 | 2 ] \s /} | / foo | bar / );'
OR
raku -ne '.put if .grep( (none /^ [ 1 | 2 ] \s /) | / foo | bar / );'
Sample Input:
1 foo
1 bar
1 someOtherString
2 contains bar and more
2 test
3 contains a random string
4 some other string
2 don't remove this line bar
2 but remove this line
14 keep this line
21 and also this line
7 bar
Sample Output:
1 foo
1 bar
2 contains bar and more
3 contains a random string
4 some other string
2 don't remove this line bar
14 keep this line
21 and also this line
7 bar
Above is a rough translation of @roaima's Perl5 code, although in Raku this is properly a grep
operation. In Raku, you can test for the absence of a pattern using either the !
negation operator (shown above with/without a surrounding {...}
codeblock), or using a none
junction (related to Sets
in Raku).
You may note the inclusion of a \s
character in the regex. That's because undeclared (\s
) whitespace and/or "...unquoted whitespace in a regex is generally ignored..." by default in Raku, making for more readable code. See links below.
https://docs.raku.org/language/regexes#Sigspace
https://raku.org
14
and21
would be removed in your example), and (2) can the pattern that would mandate keeping the line be part of the first "word" (e.g. is a line starting with1foo
possible)?