如何使用sed/awk/perl从数字中删除前导和尾随零?

to94eoyn  于 8个月前  发布在  Perl
关注(0)|答案(7)|浏览(120)

我有这样的文件:

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

在上面的文件中,我想删除前导和尾随零,因此输出将像这样

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

如何实现这一点?我尝试sed删除这些零。它很容易删除尾随零,但不是前导零。
帮帮我

zfycwa2u

zfycwa2u1#

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

6jjcrrmo2#

试试Perl:

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

  print $_;
 }
}
ipakzgxi

ipakzgxi3#

sed在行的开头查找全零+在行的末尾查找全零:

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

t1rydlwq4#

这可能对你有用(GNU sed):

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

或:

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

a1o7rhls5#

Bash示例删除尾随零

# ----------------- 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 -----------------
kdfy810k

kdfy810k6#

在fedorqui的答案上进行扩展,这一行将

  • 去掉前导零
  • 去除尾随零
    *如果存在尾随小数点且小数点后的所有数字均为0,则删除尾随小数点
  • 例如1.00 -> 1而不是1.00 -> 1.
sed -e 's/^[0]*//' -e 's/[0]*$//' -e 's/\.$//g'
rjjhvcjd

rjjhvcjd7#

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

相关问题