簡體   English   中英

管道 git 命令到 sed 輸出

[英]Pipe git command to sed output

我正在嘗試將 git 的輸出通過管道傳輸到 sed,這將替換 file.config 中代表分支上最后一次提交的值。

我不確定如何在 bash 中使用管道來做到這一點。 我想也許是這樣的? 但它不起作用(什么都不輸出)

git rev-parse --short HEAD | sed -i 's/"commit".*:.*".*"/"commit": "${$_}"/g' file.config

這甚至可能嗎,還是我可以采取更好的方法?

file.config 的內容

{
    "commit" : "684e8ba31"
}

file.config 的內容(運行命令后)

{
    "commit" : "${$_}"
}

file.config 的內容(預期輸出)

{
    "commit" : "441d6fc22"
}

來自 git rev-parse --short HEAD 的輸出

441d6fc22
sed -i '/"commit" *:/s/: *"[^"]*"/: "'$(git rev-parse HEAD)'"/' file.config

會做的。 您將命令行參數與標准輸入混淆。 它們都是提供調用程序數據的良好且廣泛使用的方法,但容量和時間的差異很重要,因此請花更多時間研究它們的工作原理。

模擬git調用的輸出:

$ cat git.out
441d6fc22

我們將git輸出捕獲到變量然后將變量提供給sed的一種想法:

$ read -r sha < <(cat git.out)
$ sed -E "s/^(.*\"commit\"[^\"]*).*/\1\"${sha}\"/" file.config
{
    "commit" : "441d6fc22"
}

在哪里:

  • -E - 啟用擴展的正則表達式支持
  • (.*\"commit\"[^\"]*) -(第一​​個捕獲組)從行首到並包括"commit"的所有內容,然后是第一次出現文字"
  • .*其余行
  • \1\"${sha}"\" - 替換為第一個捕獲組的內容,后跟文字"sha變量的內容和另一個文字"

對結果滿意后,可以添加-i選項:

$ sed -Ei "s/^(.*\"commit\"[^\"]*).*/\1\"${sha}\"/" file.config
$ cat file.config
{
    "commit" : "441d6fc22"
}

將原始git調用拉入組合:

read -r sha < <(git rev-parse --short HEAD)
sed -Ei "s/^(.*\"commit\"[^\"]*).*/\1\"${sha}\"/" file.config

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM