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

时间:2013-09-10 09:00:17

标签: perl bash sed awk

我的文件是这样的:

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删除那些零。很容易删除尾随零而不是前导零。

帮帮我。

5 个答案:

答案 0 :(得分:6)

试试这个Perl:

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

  print $_;
 }
}

答案 1 :(得分:6)

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

答案 2 :(得分:4)

sed在行的开头查找所有零,最后查找所有零:

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

答案 3 :(得分:3)

这可能适合你(GNU sed):

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

或:

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

答案 4 :(得分:0)

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

相关问题