5

在 while read line 循环中,我看到了这个变量扩展${line/device name:}。我试过用我自己的输入文件运行脚本,它只是打印出这一行。

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

4

2 回答 2

4

变量名是line。/ 用于字符串替换,即“设备名称:”如果存在于其中的任何位置$line则被删除。

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

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

于 2015-09-16T22:24:16.777 回答
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.
于 2015-09-16T22:26:00.533 回答