0

I am writing a function in zsh which has a string

"find . -a -print:10"

the :10 part needs to be trimmed off the right. This might change in the future to become :23 or :77 etc so it seems a pattern like :[0-9]+ is needed.

also, the string might have the form

find . -a -print

In which case if there is no :[0-9]+ pattern on the end, then the string should be left unchanged.

so

  • find . -a -print:10 should become find . -a -print
    and
  • find . -a -print should stay as find . -a -print

What I have tried so far

% sed -nr 's/(.*)(:[0-9]+)?/\1/p' <<<'find . -a -print:10'
find . -a -print:10     # ':10' not getting trimmed

If I try

sed -nr 's/(.*)(:[0-9]+)/\1/p' <<<'find . -a -print:10'
find . -a -print  # ':10' getting trimmed GOOD ✔✔ 

but the same sed expression

 sed -nr 's/(.*)(:[0-9]+)/\1/p' <<<'find . -a -print'
 # no output

How can I right trim this string?

  • 3
    Why would you want to use sed for this - rather than your shell's own parameter expansion capabilities (e.g. "${str%:*}")? – steeldriver Oct 04 '16 at 01:27
  • "How can I right trim a string with sed - and not kill the string if the pattern is not there?"sed doesn't kill any lines unless you tell it to. – Wildcard Oct 04 '16 at 01:30
  • at steeldriver good question, I was going to address that, but didn't want the question to be too long. its because * globs match too many characters, i.e. if the string became find -iname "foo\:bar.txt" then the glob '' in `"${str%:}"would matchbar.txt. Im surezsh` has some fancier globbing (extended globs) but I'm not experienced with them. – the_velour_fog Oct 04 '16 at 01:31
  • This is almost a duplicate of Shell test to find a pattern in a string because basically that's what you want: test if your string matches the regex :[0-9]+$ (and if it does update string value to ${string%:*}) – don_crissti Oct 04 '16 at 10:40

1 Answers1

3

Why are you using -n if you don't want to suppress the default output?

Just use:

sed -E -e 's/:[0-9]+$//'
Wildcard
  • 36,499