我正在嘗試將一系列操作通過管道傳輸到 xargs 呼叫中,我可以使用該呼叫使用 sed 命令將第一個值與第二個值交換(如果有更好的方法,sed 是可選的)。
基本上,我在駱駝案例中獲取方法簽名并在嘗試保留駱駝案例時附加前綴。
所以應該需要...
原始方法簽名
并將其替換為...
給定的原始方法簽名
因為我正在使用一系列管道來查找和修改文本,所以我希望將多個引數與 xargs 一起使用,但似乎涉及該使用的大多數問題sh -c都很好,但是為了使 sed 命令成為Mac 終端上的互動式我需要在 shell 呼叫的單引號內使用單引號。
像這樣的東西,雙引號保留了 sed 命令中單引號的功能......
echo "somePrecondition SomePrecondition" | xargs -L1 sh -c 'find ~/Documents/BDD/Definitions/ -type f -name "Given$1.swift" -exec sed -i "''" "'"s/ $0/ given$1/g"'" {} '
假設有一個名為“~/Documents/BDD/Definitions/GivenSomePrecondition.swift”的檔案,其中包含以下代碼......
protocol GivenSomePrecondition { }
extension GivenSomePrecondition {
func somePrecondition() {
print("empty")
}
}
第一個 awk 遍歷以 Given 關鍵字(例如 GivenSomePrecondition)開頭的 swift 協議串列,然后在到達最后一個管道之前將其剝離為“somePrecondition SomePrecondition”。我的意圖是最終的 xargs 呼叫可以以互動方式將 $0 替換為 given$1(覆寫檔案)。
背景關系中的原始命令...
awk '{ if ($1 ~ /^Given/) print $0;}' ~/Documents/Sell/SellUITests/BDDLite/Definitions/HasStepDefinitions.swift \
| tr -d "\t" \
| tr -d " " \
| tr -d "," \
| sort -u \
| xargs -I string sh -c 'str=$(echo string); echo ${str#"Given"}' \
| awk '{ print tolower(substr($1,1,1)) substr($1, 2)" "$1 }' \
| xargs -L1 sh -c '
find ~/Documents/Sell/SellUITests/BDDLite/Definitions/ \
-type f \
-name "Given$1.swift" \
-exec sed -i '' "'"s/ $0/ given$1/g"'" {} '
uj5u.com熱心網友回復:
您不需要xargsor sh -c,去掉它們可以減少所涉及的作業量。
echo "somePrecondition SomePrecondition" |
while read -r source replace; do
find ~/Documents/BDD/Definitions/ -type f -name "Given${replace}.swift" -print0 |
while IFS= read -r -d '' filename; do
sed -i '' -e "s/ ${source}/ given${replace}/g" "$filename"
done
done
但是,要回答您的問題而不是回避它,您可以撰寫使用您想要的任何型別的引號的函式,并將它們匯出到您的子 shell,無論是export -f yourFunction在父行程中還是通過放入"$(declare -f yourFunction)"之后傳遞的字串bash -c(假設bash是定義這些函式的父行程中使用的相同 shell )。
#!/usr/bin/env bash
replaceOne() {
local source replace
source=$1; shift || return
replace=$1; shift || return
sed -i '' -e "s/ $1/ given$2/g" "$@"
}
# substitute replaceOne into a new copy of bash, no matter what kind of quotes it has
bash -c "$(declare -f replaceOne)"'; replaceOne "$@"'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347830.html
