bash 如何使用 sed/awk/perl 从数字中删除前导零和尾随零?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18714645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I remove leading and trailing zeroes from numbers with sed/awk/perl?
提问by EngineSense
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.
如何实现这一目标?我试图sed
删除那些零。删除尾随零很容易,但不能删除前导零。
Help me.
帮我。
回答by Сухой27
perl -pe 's/^0+ | 0+$//xg' numbers
回答by rams0610
try this Perl:
试试这个 Perl:
while (<>) {
$_ =~ s/(^0+|0+$)//g;
print $_;
}
}
回答by fedorqui 'SO stop harming'
sed
looking for all zeros in the beginning of the line + looking for all zeros in the end:
sed
在行首寻找全零 + 在最后寻找全零:
$ sed -e 's/^[0]*//' -e 's/[0]*$//g' numbers
1234567891
2133123131
4324234243
4356257472
3465645768
3424242423
3543676586
3564578765
6585645646
1212122
1212121122
3232322
回答by potong
This might work for you (GNU sed):
这可能对你有用(GNU sed):
sed 's/^00*\|00*$//g' file
or:
或者:
sed -r 's/^0+|0+$//g' file
回答by Zimba
Bash example to remove trailing zeros
删除尾随零的 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 -----------------