使用sed(或类似方法)修改变量的内容 [英] Modify the content of variable using sed (or something similar)
问题描述
我写了一个BASH文件,其中包含多个嵌入式循环,形式为
I wrote a BASH file that features multiple embedded loops of the form
for P in {'0.10','0.20', [...] '0.90','1.00'}; do
for Q in {'0.10','0.20', [...] ,'0.90','1.00'}; do
[...]
我将这些变量用作命令行应用程序的参数,并直接在BASH中创建文件名.我想创建重复项,例如 $ P_REP = 0_10
,该重复项用下划线替换点,而无需为每种情况或某些硬编码的等效项编写明确的switch语句.我发现解决该问题的(非优雅方法)是
I use these variables both as parameters for a command line application, and to create file names directly in BASH. I would like to create duplicates, say $P_REP=0_10
that replaces the dot by an underscore without writting a explicit switch statement for every case, or some hardcoded equivalent. The (non-elegant way) I found to go about it is to
- 将
P,Q
的内容转储到临时文件中. - 使用
sed的s/./_/-i
在下划线处替换点. - 再次读取文件并将其内容加载到新变量中.
- dump the content of
P,Q
to a temporary file. - replace the dot by an underscore using
sed 's/./_/ -i
. - read the file again and load its content to the new variable.
因此,我想知道是否可以直接在变量的内容上运行sed like命令吗?
Hence, I was wondering if it is possible to run a sed like command directly on the content of a variable?
推荐答案
您可以直接在bash中进行模式替换:
You can do pattern substitution directly in bash:
P_REP=${P/./_}
Q_REP=${Q/./_}
在bash(1)手册页中:
From the bash(1) man page:
参数扩展
$ {parameter/pattern/string}
Paramter Expansion
${parameter/pattern/string}
模式替换.扩展 pattern 来生成模式,就像在路径名扩展中一样.参数被扩展,并且 pattern 与其值的最长匹配被替换为 string .如果 pattern 以/
开头,则所有 pattern 匹配项都将替换为 string .通常只替换第一个比赛.如果 pattern 以#
开头,则它必须与参数的扩展值的开头匹配.如果 pattern 以%
开头,则它必须在参数的扩展值的末尾匹配.如果 string 为null,则删除 pattern 的匹配项,并且/后面的 pattern 可以省略.如果参数是 @
或 *
,则将替换操作依次应用于每个位置参数,并且扩展名是结果列表.如果parameter是一个用 @
或 *
下标的数组变量,则将替换操作依次应用于该数组的每个成员,并且扩展为结果列表.>
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.
这篇关于使用sed(或类似方法)修改变量的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!