在 shell 脚本中查找和替换(特殊字符)

Find and replace in shell script (special characters)

我是 shell 脚本编写新手:

我有以下内容:

old=/dev/sda
new=/dev/sda5

鉴于这些变量,我需要从 "new" 字符串中提取 5

我该怎么办? sedawk?

尝试使用:

partitionno=$(echo $new | sed 's/$old//g')

要以最少的命令更改获得正确的结果,请尝试:

partitionno=$(echo "$new" | sed "s|$old||g")

这里有两个重点:

  1. Shell 变量不会在单引号内展开。所以'$old'仍然是原来的四个字符:$old。对于要展开的shell变量,使用双引号。

  2. sed "s/$old//g" 还是不行,因为斜杠太多了。替换命令使用三个斜线。 shell展开$old后,有五个斜杠。解决方案是为替换命令使用不同的定界符。我在上面选择了 |,因为 | 不太可能出现在文件名中。

使用Shell Parameter Expansion

$ old=/dev/sda
$ new=/dev/sda5
$ echo "${new#$old}"
5

${parameter#word}

${parameter##word}

The word is expanded to produce a pattern just as in filename expansion (see Filename Expansion). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal 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 pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.