Bash变量扩展中的'/'

5

在一个while read line循环里,我看到这个变量扩展 ${line/device name:}。我尝试用自己的输入文件运行脚本,它只是打印出该行。你能告诉我这个扩展是做什么的吗?


两个答案都是正确的,但这里有关于参数扩展的文档,以供日后参考和编辑到答案中:http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html - Jeff Bowman
2个回答

4

变量名是 line。/ 用于字符串替换,即如果在 $line任何位置存在 "设备名称:",则将其移除。

> line="a device name: some name"
> echo ${line/device name:}
a  some name

您可能还会看到#%替换,它们代表的开头和结尾的替换。请注意,这种/替换是bash特有的功能(例如,ash不支持它,%#似乎是可移植的),因此您应该在脚本开头使用#!/bin/bash而不是#!/bin/sh作为哈希标记。


%#确实是可移植的,它们是POSIX shell规范的一部分。 - chepner
谢谢。答案很好! - Jimbo

3
它返回去除子字符串“device name:”后的$line。来自Bash手册页面:
${parameter/pattern/string}
       Pattern substitution.  The pattern is expanded to produce a pattern just as in
       pathname  expansion.   Parameter  is expanded and the longest match of pattern
       against its value is replaced with string.  If  pattern  begins  with  /,  all
       matches of pattern are replaced with string.  Normally only the first match is
       replaced.  If pattern begins with #, it must match at  the  beginning  of  the
       expanded  value  of parameter.  If pattern begins with %, it must match at the
       end of the expanded value of parameter.  If string is null, matches of pattern
       are  deleted and the / following pattern may be omitted.  If parameter is @ or
       *, the substitution operation is applied to each positional parameter in turn,
       and  the  expansion  is the resultant list.  If parameter is an array variable
       subscripted with @ or *, the substitution operation is applied to each  member
       of the array in turn, and the expansion is the resultant list.

谢谢。非常好的答案! - Jimbo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接