【问题标题】:Bash variable expansion with a '/'使用 '/' 的 Bash 变量扩展
【发布时间】:2015-12-13 16:43:00
【问题描述】:

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

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

【问题讨论】:

标签: bash variable-expansion parameter-expansion


【解决方案1】:

变量名是line。 / 用于字符串替换,即“设备名称:”如果存在 anywhere$line 被删除。

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

您可能还会看到#% 替换,它们代表line 开始和结束中的替换。还要注意这种/ 替换是bash 特有的功能(例如ash 不支持它,%# 似乎是可移植的),所以你应该使用#!/bin/bash 而不是#!/bin/sh 作为脚本开头的 hashbang。

【讨论】:

【解决方案2】:

它返回 $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.

【讨论】:

  • 谢谢。很好的答案!
猜你喜欢
  • 1970-01-01
  • 2012-03-17
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 2021-03-08
  • 2019-11-24
  • 2017-08-18
  • 2012-03-09
相关资源
最近更新 更多