在终端中“子跟踪”字符串变量的最简单方法?

在终端中“子跟踪”字符串变量的最简单方法?

让我们假设我们有一个$test保存值的变量asd 123——例如,切割asd零件的最简单方法是什么?

我用 Google 搜索了这个问题一段时间但很惊讶我找不到答案。

答案1

在类似 Bourne 的 shell 中,例如dash/bin/sh在 Ubuntu 上),bash还有ksh一种叫做参数扩展,并且是 POSIX 标准指定的功能。具体来说,引用手册dash

 ${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.

因此,要替换asd零件,您可以执行以下操作:

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

要删除123你可以这样做:

$ echo ${var%*123}
asd

bash更进一步,使用另一种形式:${parameter/string/replacement}and ${parameter//string/replacement}。第一种形式替换字符串的第一次出现。第二种形式替换所有出现的情况。例如:

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

请注意,根据语法,该replacement部分是空字符串

相关内容