开发者

How to delete all characters but the last

I want to parse a file and delete all leading开发者_C百科 0's of a number using sed. (of course if i have something like 0000 then results to 0) How to do that?


I think you may be searching for this.
Here lies your answer. You need to modify of course.

  • How to remove first/last character from a string using SED


This is probably over complicated, but it catches all the corner cases I tested:

sed 's/^\([^0-9]*\)0/\1\n0/;s/$/}/;s/\([^0-9\n]\)0/\1\n/g;s/\n0\+/\n/g;s/\n\([^0-9]\)/0\1/g;s/\n//g;s/}$//' inputfile

Explanation:

This uses the divide-and-conquer technique of inserting newlines to delimit segments of a line so they can be manipulated individually.

  • s/^\([^0-9]*\)0/\1\n0/ - insert a newline before the first zero
  • s/$/}/ - add a buffer character at the end
  • s/\([^0-9\n]\)0/\1\n/g - insert newlines before each leading zero (and remove the first)
  • s/\n0\+/\n/g - remove the remaining leading zeros
  • s/\n\([^0-9]\)/0\1/g - replace bare zeros
  • s/\n//g - remove the newlines
  • s/}$// - remove the end-of-line buffer

This file:

0 foo 1 bar 01 10 001 baz 010 100 qux 000 00 0001 0100 0010
100 | 00100
010 | 010
001 | 001
100 | 100
0 | 0
00 | 0
000 | 0
00 | 00
 00 | 00
00 | 00 z

Becomes:

0 foo 1 bar 1 10 1 baz 10 100 qux 0 0 1 100 10
100 | 100
10 | 10
1 | 1
100 | 100
0 | 0
0 | 0
0 | 0
0 | 0
 0 | 0
0 | 0 z


If you have leading zeroes and it is accompanied by string of numbers, all you have to do is to convert it into integer. Something like this

$ echo "000123 test " | awk '{$1=$1+0}1'
123 test

This will not require any significant amount of regex whether they are simple or overly complicated.

Similarly (Ruby1.9+)

$ echo "000123 test " | ruby -lane '$F[0]=$F[0].to_i; print $F.join(" ")'
123 test

For cases of all 0000's

$ echo "0000 test " | ruby -lane '$F[0]=$F[0].to_i; print $F.join(" ")'
0 test
$ echo "000 test " | awk '{$1=$1+0}1'
0 test
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜