1

Let's assume that we've a variable $test which holds a value asd 123 - what is the most simplest way to cut, for example, asd part?

I've googled this for awhile and surprised that I couldn't find an answer.

1 Answers1

2

In Bourne-like shells, such as dash ( /bin/sh on Ubuntu ), bash and ksh there is something known as parameter expansion, and is a feature specified by POSIX standard. Specifically, to quote dash manual:

 ${parameter%word}     Remove Smallest Suffix Pattern.  The word is expanded to produce a pattern.  The parameter expansion then results in parameter, with the smallest
                       portion of the suffix matched by the pattern deleted.

 ${parameter%%word}    Remove Largest Suffix Pattern.  The word is expanded to produce a pattern.  The parameter expansion then results in parameter, with the largest
                       portion of the suffix matched by the pattern deleted.

 ${parameter#word}     Remove Smallest Prefix Pattern.  The word is expanded to produce a pattern.  The parameter expansion then results in parameter, with the smallest
                       portion of the prefix matched by the pattern deleted.

 ${parameter##word}    Remove Largest Prefix Pattern.  The word is expanded to produce a pattern.  The parameter expansion then results in parameter, with the largest
                       portion of the prefix matched by the pattern deleted.

Thus, to replace asd part you can do:

$ var="asd 123"
$ echo ${var#asd*}
123

To remove 123 you can do:

$ echo ${var%*123}
asd

bash goes even further with this with another form: ${parameter/string/replacement} and ${parameter//string/replacement}. First one replaces first occurrence of string. Second form replaces all occurrences. For instance:

$ echo ${var//123/}
asd
$ echo ${var//asd/}
123

Note that according with the syntax, the replacement part is empty string

Sergiy Kolodyazhnyy
  • 105,154
  • 20
  • 279
  • 497