Skip to content

Instantly share code, notes, and snippets.

@W-Floyd
Created April 12, 2018 01:28
Show Gist options
  • Save W-Floyd/8155911e27b92235fd47821c8aaa4de0 to your computer and use it in GitHub Desktop.
Save W-Floyd/8155911e27b92235fd47821c8aaa4de0 to your computer and use it in GitHub Desktop.
A one-liner sed expression to nicely strip leading and trailing 0's from each line of piped input
################################################################################
# ... | __zero_strip
################################################################################
#
# Zero Strip
#
# A one-liner sed expression to nicely strip leading and trailing 0's from each
# line of piped input.
#
# For example:
#
# echo '1.0
# 5.000
# 9.0001
# 50.60
# 7.24235
# .9000
# .00001' | __zero_strip
#
# Generates:
#
# 1
# 5
# 9.0001
# 50.6
# 7.24235
# 0.9
# 0.00001
#
################################################################################
__zero_strip () {
cat | sed -e 's|\(\..*[^0]\)0\{1,\}$|\1|' -e 's|\.0*$||' -e 's|^0*||' -e 's|^\.|0.|' -e 's|^$|0|'
}
@W-Floyd
Copy link
Author

W-Floyd commented Apr 12, 2018

Corner Cases

If input is a blank line, or just ., 0 will be the result.
There is no special handling of non-numeric characters, they'll be treated like numbers 1-9.

Explanation

's|\(\..*[^0]\)0\{1,\}$|\1|'

Find the part of the string starting with ., matching any characters up until a character other than 0.
This part of the string will be kept (hence the \1 in the replace section).
This saved portion of the match must then be followed by one or more 0s, (the \{1,\} is the same as + - extended regex wasn't working for me, so this is fine), up until the end of the line.

Note that is takes advantage of the greedy nature of sed, so it will match the last non-zero character.

This means lines such as

0.9000
5.0001000
9.9140

will be stripped of their trailing 0s, to become

0.9
5.0001
9.914

As they should.
Note, however, that this match does not correct pure trailing 0s, such as

6.000
266.000
1.0

As a non-0 character following the decimal place must occur at some point.


's|\.0*$||'

This is quite simple, it matched a period followed by all 0s until end of line.
This takes care of the caveat mentioned above, so

6.000
266.000
1.0

is correctly stripped to

6
266
1

's|^0*||'

Similar to above, strip leading 0s.
Means

0005
0004.245
00000.1

Becomes

5
4.245
.1

's|^\.|0.|'

This is just to make output pretty, makes sure one leading 0 is present if no other number is there in front of the decimal place.
Example:

.01
.9

Becomes

0.01
0.9

This is more about my preference, not strictly necessary.


's|^$|0|'

This cleans up in case input was 0, in some form.
Examples of 0s that would otherwise result in empty lines

0
0.0
0000.0000

This match makes sure that if no characters were present at the end, a 0 is there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment