Reputation: 3616
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
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
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
Reputation: 3
Expanding on the answer by fedorqui, this one-liner will
1.00 -> 1
instead of 1.00 -> 1.
sed -e 's/^[0]*//' -e 's/[0]*$//' -e 's/\.$//g'
Upvotes: 0
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
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