Shell中如何替換一個字元來得到多個字串?

Shell中如何替換一個字元來得到多個字串?

我可以找到許多問題,並在另一個方向上找到答案,但不幸的是,不是我想要的替代品:我打算替換一個字符, 例如#在一個字串中,例如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

解決這個問題的工作方法是什麼?

編輯,因為我可能還沒有評論:我必須#在字符串中使用,其中應該替換該字符,因為字符串是從另一個程序傳遞的。不過,我可以先用另一個字元替換它。

答案1

運算{0..10} zsh子(現在也被其他一些 shell 支持,包括bash)只是csh-style 大括號擴展的另一種形式。

已擴大透過外殼在調用命令之前。該命令看不到這些{0..10}

With tr '#' {0..10}(引用它,#否則它會被 shell 解析為註解的開頭),tr以 ("tr", "#", "0", "1", ..., "10") 作為參數呼叫結束並且tr不希望有那麼多爭論。

在這裡,您想要:

echo '_'{0..10}'.test' 

用於echo傳遞“_0.test”、“_1.test”、...、“_10.test”作為參數。

或者,如果您希望將其#轉換為該{0..10}運算符,請將其轉換為要計算的 shell 程式碼:

eval "$(echo 'echo _#.test' | sed 's/#/{0..10}/')"

作為參數eval傳遞到哪裡。echo _{0..10}.test

(並不是說我會建議做類似的事情)。

答案2

你可以分裂分隔符號上的字串,捕獲前綴和後綴,然後使用大括號擴展來產生名稱:

str='test#asdf'
IFS='#' read -r prefix suffix <<<"$str"
names=( "$prefix"{0..10}"$suffix" )
declare -p names
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")'

答案3

你必須使用嗎#?也許你可以用%d

$ for i in {1..10}; do printf "_%d.test " "$i"; done
_1.test _2.test _3.test _4.test _5.test _6.test _7.test _8.test _9.test _10.test

答案4

我會這樣做參數擴充

$ var='test#asdf'
$ for i in {1..10}; do echo "${var/\#/"$i"}"; done
test1asdf
test2asdf
test3asdf
test4asdf
test5asdf
test6asdf
test7asdf
test8asdf
test9asdf
test10asdf

擴張${parameter/pattern/string}

  • 進行(在我們的例子中, )的展開並且$parameter$var
  • 替換第一次出現的pattern(轉義#/#在上下文中具有特殊含義,“在字串的開頭替換”,我們要避免)
  • string"$i"在我們的例子中)

或者,您可以將 替換#%d並將其用作 的格式字串printf

printf "${var/\#/%d}\\n" {1..10}

相關內容