Johan van Marion
Johan van Marion

Reputation: 11

How to replace "leading zero" witin a string

How can i replace or remove "0" from a string in bash The string is based in [prefix][ID][suffix] e.g. ZZZ00004500AA010 or ZZZ004500AA010 the result must be ZZZ4500AA010 so i want to remove the leading 0's in the ID At the moment i have this:

echo "ZZZ00004500AA010" | sed 's/0//'
echo "ZZZ004500AA010" | sed 's/0//'

which gives me : ZZZ0004500AA010 or ZZZ04500AA010

Upvotes: 1

Views: 136

Answers (3)

Timur Shtatland
Timur Shtatland

Reputation: 12347

Use this Perl one-liner:

$ echo "ZZZ00004500AA010" | perl -pe 's{^([A-Za-z]+)0+}{$1}'
ZZZ4500AA010

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{PATTERN}{REPLACEMENT} : Change PATTERN to REPLACEMENT.
^ : Beginning of the string.
([A-Za-z]+) : Match any letter repeated 1 or more times. Capture into capture group 1 ($1).
0+ : zero, repeated 1 or more times.

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
perldoc perlrequick: Perl regular expressions quick start

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163362

You can use a capture group to match the leading chars other than a digit, and then match 0 or more digits.

In the replacement use group 1.

^([^0-9]*)0+

Regex demo

echo "ZZZ00004500AA010" | sed -E 's/^([^0-9]*)0+/\1/'
echo "ZZZ004500AA010" | sed -E 's/^([^0-9]*)0+/\1/'

Output

ZZZ4500AA010
ZZZ4500AA010

If there have to be leading chars A-Z:

^([A-Z]+)0+

Regex demo

Upvotes: 1

choroba
choroba

Reputation: 241898

If you know there's always at least one zero, you don't need sed at all, you can use parameter expansion. You can use a regex match to check there is a zero after the initial non-digits:

#! /bin/bash
shopt -s extglob
for v in ZZZ00004500AA010 ZZZ004500AA010 ZZZ04500AA010 ZZZ4500AA010 ; do
    if [[ $v =~ ^[^0-9]+0 ]] ; then
        v=${v/+(0)/}
    fi
    echo "$v"
done

Output:

ZZZ4500AA010
ZZZ4500AA010
ZZZ4500AA010
ZZZ4500AA010

Upvotes: 1

Related Questions