使用'/'进行Bash变量扩展

时间:2015-09-16 22:19:12

标签: bash variable-expansion parameter-expansion

在一段时间的读取行循环中,我看到了这个变量扩展${line/device name:}。我已经尝试使用自己的输入文件运行脚本,它只打印出行。

你能告诉我扩展正在做什么吗?

2 个答案:

答案 0 :(得分:4)

变量名称为line。 /用于字符串替换,即&#34;设备名称:&#34;如果<{1}}中存在 ,则

$line

您可能还会看到> line="a device name: some name" > echo ${line/device name:} a some name #替换,代表%开头和结尾的替换。还要注意这种line替换是特定于bash的功能(例如/不支持它,ash%看起来很便携,所以你应该在脚本的开头使用#代替#!/bin/bash作为hashbang。

答案 1 :(得分:4)

返回$line,删除子字符串device name:。从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.