Sed regexp looking for either whitespace or end of line

前端 未结 3 1949
遇见更好的自我
遇见更好的自我 2021-01-19 12:38

I\'m trying to detect a pattern that has three parts:

  1. A space
  2. Either an \"m\" or a \"t\"
  3. Either a space or the end of a line

I

相关标签:
3条回答
  • 2021-01-19 12:58

    Space or end of line? Use |:

    s/ \([mt]\)\( \|$\)/\1\2/g
    
    0 讨论(0)
  • 2021-01-19 13:10

    Just matching space, then m or t, then space or newline won't catch cases with punctuation, e.g. a missing ' in "please don t!". A more general solution is to use word boundaries instead:

    echo "i m sure he doesn t test test don t." | sed 's/ \([mt]\)[[:>:]]/\1/g'
    

    The funky [[:>:]] is required on OS X (which I use), see Larry Gerndt's answer to sed whole word search and replace. On other sed flavors you may be able to use \b (any word boundary) or \> instead.

    # example with word boundary
    echo "i m sure he doesn t test test don t." | sed 's/ \([mt]\)[[:>:]]/\1/g'
    im sure he doesnt test test dont.
    
    0 讨论(0)
  • 2021-01-19 13:16

    Make last space optional:

    sed 's/[ ]\([mt][ ]\?\)$/\1/' input
    

    Posix friendly version:

    sed 's/[ ]\([mt][ ]\{,1\}\)$/\1/' input
    
    0 讨论(0)
提交回复
热议问题