EngineSense
EngineSense

Reputation: 3616

How can I remove leading and trailing zeroes from numbers with sed/awk/perl?

I have file like this:

pup@pup:~/perl_test$ cat numbers 
1234567891
2133123131
4324234243
4356257472
3465645768000
3424242423
3543676586
3564578765
6585645646000
0001212122
1212121122
0003232322

In the above file I want to remove the leading and trailing zeroes so the output will be like this

pup@pup:~/perl_test$ cat numbers 
1234567891
2133123131
4324234243
4356257472
3465645768
3424242423
3543676586
3564578765
6585645646
1212122
1212121122
3232322

How to achieve this? I tried sed to remove those zeroes. It was easy to remove the trailing zeroes but not the leading zeroes.

Help me.

Upvotes: 7

Views: 13228

Answers (7)

fedorqui
fedorqui

Reputation: 289525

sed looking for all zeros in the beginning of the line + looking for all zeros in the end:

$ sed -e 's/^0+//' -e 's/0+$//' numbers
1234567891
2133123131
4324234243
4356257472
3465645768
3424242423
3543676586
3564578765
6585645646
1212122
1212121122
3232322

Upvotes: 8

mpapec
mpapec

Reputation: 50637

perl -pe 's/ ^0+ | 0+$ //xg' numbers

Upvotes: 8

RARE Kpop Manifesto
RARE Kpop Manifesto

Reputation: 2809

gawk ++NF FS='^0+|0+$' OFS=
mawk 'gsub("^0*|0*$",_)'   # using [*] instead of [+] here
                           # ensures all rows print

1234567891
2133123131
4324234243
4356257472
3465645768
3424242423
3543676586
3564578765
6585645646
1212122
1212121122
3232322

Upvotes: 0

jcs
jcs

Reputation: 3

Expanding on the answer by fedorqui, this one-liner will

  • strip leading zeroes
  • strip trailing zeroes
  • strip a trailing decimal point if one exists and all numerals following the decimal are 0
    • e.g. 1.00 -> 1 instead of 1.00 -> 1.
sed -e 's/^[0]*//' -e 's/[0]*$//' -e 's/\.$//g'

Upvotes: 0

Zimba
Zimba

Reputation: 3683

Bash example to remove trailing zeros


    # ----------------- bash to remove trailing zeros ------------------
    # decimal insignificant zeros may be removed
    # bash basic, without any new commands eg. awk, sed, head, tail
    # check other topics to remove trailing zeros
    # may be modified to remove leading zeros as well

    #unset temp1

    if [ $temp != 0 ]           ;# zero remainders to stay as a float
    then

    for i in {1..6}; do             # modify precision in both for loops

    j=${temp: $((-0-$i)):1}         ;# find trailing zeros

    if [ $j != 0 ]              ;# remove trailing zeros
    then
        temp1=$temp1"$j"
    fi
        done
    else 
        temp1=0
    fi

    temp1=$(echo $temp1 | rev)
    echo $result$temp1

    # ----------------- END CODE -----------------

Upvotes: 0

rams0610
rams0610

Reputation: 1051

try this Perl:

while (<>) {     
  $_ =~ s/(^0+|0+$)//g;

  print $_;
 }
}

Upvotes: 7

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed 's/^00*\|00*$//g' file

or:

 sed -r 's/^0+|0+$//g' file

Upvotes: 3

Related Questions