SED: Pattern repitition regex matching

Fairly straightforward, but I'm having an awful time getting what I thought was a simple regex to work. I'll give the command I was playing with, and I'm aware why this one doesn't work (the 1,3 is off the A-Z, not the whole expression), I just don't know what the fix is:

Actual Output(s):

$ echo "This is a test 0A2B9C 0A 3B4C" | sed 's/[0-9][A-Z]\{1,3\}/X/g'
This is a test XXX X XX
$ echo "This is a test 0A2B9C 0A 3B4C" | sed 's/[0-9][A-Z]\{1,3\}/X/' 
This is a test X2B9C 0A 3B4C

Desired Output:

This is a test X X X

Thanks, just banging my head on this one.

It's considering [0-9] and [A-Z] as separate ranges. So what you're asking for is actually a number, followed by one to three letters.

Try [0-9A-Z]

I think he's looking for 1, 2, or 3 occurrence of a digit followed by an uppercase letter:

echo "This is a test 0A2B9C 0A 3B4C" | sed 's/\([0-9][A-Z]\)\{1,3\}/X/g'
1 Like

Thanks so much, that's what I was looking for.

Edit: It works on Linux & AIX (Pretty sure it's running off GNU SED), doesn't work on Solaris by default. Any tips on Solaris, or alternate syntax? If it's not possible without GNU SED that's fine, just checking up.

# uname -s
SunOS
# echo "This is a test 0A2B9C 0A 3B4C" | sed 's/\([0-9][A-Z]\)\{1,3\}/X/g'
This is a test 0A2B9C 0A 3B4C

vs. Linux

$ uname -s
Linux
$ echo "This is a test 0A2B9C 0A 3B4C" | sed 's/\([0-9][A-Z]\)\{1,3\}/X/g'
This is a test X X X

vs. AIX:

# uname -s
AIX
# rpm -qa|grep sed
sed-4.1.1-1
# echo "This is a test 0A2B9C 0A 3B4C" | sed 's/\([0-9][A-Z]\)\{1,3\}/X/g'     
This is a test X X X

I no longer have ready access to a Solaris system, but:

sed 's/\([0-9][A-Z]\)\{1,3\}/X/g'

is using standard Basic Regular Expression notation. If /usr/bin/sed doesn't work, you might try /usr/xpg4/bin/sed, but I don't see anything in Oracle's Solaris 11 sed(1) man page indicating that this substitute command shouldn't work in both versions of sed.

1 Like

Definitely doesn't work off-the-bat with 10, at least - however I didn't know about the xpg4 binaries and that version of sed -did- work, so I'm good to go. Thanks a lot!