1

I've a string that ends with an even number of 0's padded to it. I want to remove these 0's by a regular expression (00)*:

ababababab000000 => ababababab
abababab00       => abababab
abab000000000    => abab0
aba00000         => aba0

How can this be done in Bash? In general, how would I remove any suffix using a regex?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Shuzheng
  • 11,288
  • 20
  • 88
  • 186
  • What efforts did you make? We can help you out, if you make some attempts to start with – Inian May 31 '18 at 09:20
  • See also [Unix.SE: How to detect end of line with sed](https://unix.stackexchange.com/questions/206922/how-to-detect-end-of-line-with-sed). – John Kugelman May 31 '18 at 09:26

2 Answers2

2

Use sed -r to search and replace arbitrary regexes with s/regex/replacement/. $ anchors the regex to the end of each line.

$ sed -r 's/(00)*$//' <<< 'ababababab000000'
ababababab
$ sed -r 's/(00)*$//' <<< 'abababab00'
abababab
$ sed -r 's/(00)*$//' <<< 'abab000000000'
abab0
$ sed -r 's/(00)*$//' <<< 'aba00000'
aba0
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0
$ echo ababababab000000 abababab00 abab000000000 aba00000 | sed 's/00//g'
ababababab abababab abab0 aba0
Alex Stiff
  • 844
  • 5
  • 12