Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

16
  • 16
    This is native shell string manipulation, so no additional processes will be spawned. Reference Bash Parameter Substitution, Bash String Manipulation and Better Bash Scripting Commented Apr 14, 2014 at 3:13
  • @denniswilliamson How could I deleted 2 characters after a specific string like hello:world will become hello:wo by using ${a%:*}?
    – 3kstc
    Commented Jun 25, 2016 at 13:05
  • 1
    Great answer, thanks a lot, but it will be nice to also add "${a##*:}" for getting only tomorrow =)
    – avtomaton
    Commented Nov 28, 2016 at 1:40
  • 1
    @openCivilisation: You probably need to use regular expression matching then: a='hello:world:of:tomorrow'; pattern=''^([^:]*:).*$'; [[ $a =~ $pattern ]]; echo "${BASH_REMATCH[1]}"`. That matches only if there is a colon. If you want that to be optional, a different pattern would have to be used. An explanation of Bash regexes (and regexes in general) is beyond the scope of these comments. You can find other questions that discuss this or post your own. Commented Mar 10, 2019 at 16:41
  • 1
    @kp123: It's the first example in my answer. The second time I show it (where "tomorrow" is removed), it's almost exactly the situation you're asking about. Commented Aug 28, 2019 at 21:29