Peter F
Peter F

Reputation: 61

sed regex with alternative on Solaris doesn't work

Currently I'm trying to use sed with regex on Solaris but it doesn't work. I need to show only lines matching to my regex.

sed -n -E '/^[a-zA-Z0-9]*$|^a_[a-zA-Z0-9]*$/p'

input file:

grtad
a_pitr
_aupa
a__as
baman
12353
ai345
ki_ag
-MXx2
!!!23
+_)@*

I want to show only lines matching to above regex:

grtad
a_pitr
baman
12353
ai345

Is there another way to use alternative? Is it possible in perl? Thanks for any solutions.

Upvotes: 2

Views: 962

Answers (2)

Sundeep
Sundeep

Reputation: 23667

with grep

$ grep -xiE '(a_)?[a-z0-9]*' ip.txt
grtad
a_pitr
baman
12353
ai345
  • -x match whole line
  • -i ignore case
  • -E extended regex, if not available, use grep -xi '\(a_\)\?[a-z0-9]*'
  • (a_)? zero or one time match a_
  • [a-z0-9]* zero or more alphabets or numbers


With sed

sed -nE '/^(a_)?[a-zA-Z0-9]*$/p' ip.txt

or, with GNU sed

sed -nE '/^(a_)?[a-z0-9]*$/Ip' ip.txt

Upvotes: 1

zdim
zdim

Reputation: 66881

With Perl

perl -ne 'print if /^(a_)?[a-zA-Z0-9]*$/' input.txt

The (a_)? matches a_ one-or-zero times, so optionally. It may or may not be there.

The (a_) also captures the match, what is not needed. So you can use (?:a_)? instead. The ?: makes () only group what is inside (so ? applies to the whole thing), but not remember it.

Upvotes: 1

Related Questions