Ber*_*dio 5 bash sed shell-script
我可以找到在其他方向上回答了许多问题,但遗憾的是没有一个我希望有我的替代品:我打算更换一个字符,例如#,在一个字符串,例如test#asdf,具有序列,如{0..10} 以获取字符串序列,在本例中test0asdf test1asdf test2asdf test3asdf test4asdf test5asdf test6asdf test7asdf test8asdf test9asdf test10asdf。
我尝试过,来自其他人:
echo '_#.test' | tr # {0..10} (抛出用法)echo '_#.test' | sed -r 's/#/{0..10}/g'(返回_{0..10}.test)echo '_#.test' | sed -r 's/#/'{0..10}'/g'(适用于第一个,之后我得到sed: can't read (...) no such file or directory)这个问题的工作方法是什么?
编辑,因为我可能还没有评论:我必须#在字符串中使用,这个字符应该被替换,作为从另一个程序传递的字符串。不过,我可以先用另一个字符替换它。
该{0..10} zsh运营商(现在也被一些其他的壳,包括支持bash)是另一种形式csh式的括号展开。
它在调用命令之前由 shell展开。该命令看不到那些{0..10}.
与tr '#' {0..10}(引用#否则它被外壳程序解析为注释的开始),tr以(“tr”,“#”,“0”,“1”,...,“10”)作为参数调用结束并且tr不希望有那么多争论。
在这里,你会想要:
echo '_'{0..10}'.test'
Run Code Online (Sandbox Code Playgroud)
为echo传递“_0.test”,“_1.test”,......,“_10.test”作为参数。
或者,如果您希望#将其转换为该{0..10}运算符,请将其转换为要评估的 shell 代码:
eval "$(echo 'echo _#.test' | sed 's/#/{0..10}/')"
Run Code Online (Sandbox Code Playgroud)
where作为参数eval传递echo _{0..10}.test。
(并不是说我会建议做类似的事情)。
您可以在分隔符上拆分字符串,捕获前缀和后缀,然后使用大括号扩展生成名称:
str='test#asdf'
IFS='#' read -r prefix suffix <<<"$str"
names=( "$prefix"{0..10}"$suffix" )
declare -p names
Run Code Online (Sandbox Code Playgroud)
declare -a names='([0]="test0asdf" [1]="test1asdf" [2]="test2asdf" [3]="test3asdf" [4]="test4asdf" [5]="test5asdf" [6]="test6asdf" [7]="test7asdf" [8]="test8asdf" [9]="test9asdf" [10]="test10asdf")'
Run Code Online (Sandbox Code Playgroud)