Created
April 12, 2018 01:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################################################ | |
# ... | __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|' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 than0
.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
0
s, (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
will be stripped of their trailing
0
s, to becomeAs they should.
Note, however, that this match does not correct pure trailing
0
s, such asAs 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
0
s until end of line.This takes care of the caveat mentioned above, so
is correctly stripped to
's|^0*||'
Similar to above, strip leading
0
s.Means
Becomes
'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:
Becomes
This is more about my preference, not strictly necessary.
's|^$|0|'
This cleans up in case input was
0
, in some form.Examples of
0
s that would otherwise result in empty linesThis match makes sure that if no characters were present at the end, a
0
is there.