基本上foo(**bar)在python中做什么,在這里我想要類似的東西
foo **bar.yaml
那會變成
foo --bar1=1 --bar2=2
bar.yaml會在哪里
bar1: 1
bar2: 2
uj5u.com熱心網友回復:
你可以使用的組合sed和xargs:
sed -E 's/^(. ):[[:space:]] (. )$/--\1=\2/' bar.yaml | xargs -d '\n' foo
sed轉換行的格式bar.yaml(例如bar1: 1-> --bar1=1)并將xargs轉換后的行作為引數提供給foo.
您當然可以修改/擴展sed部件以支持其他格式或單破折號選項,如-v.
要測驗這是否符合您的要求,您可以運行此 Bash 腳本而不是foo:
#!/usr/bin/env bash
echo "Arguments: $#"
for ((i=1; i <= $#; i )); do
echo "Argument $i: '${!i}'"
done
uj5u.com熱心網友回復:
這是zsh. 運行此代碼或將其添加到~/.zshrc:
function _yamlExpand {
setopt local_options extended_glob
# 'words' array contains the current command line
# yaml filename is the last value
yamlFile=${words[-1]}
# parse 'key : value' lines from file, create associative array
typeset -A parms=("${(@s.:.)${(f)"$(<${yamlFile})"}}")
# trim leading and trailing whitespace from keys and values
# requires extended_glob
parms=("${(kv@)${(kv@)parms##[[:space:]]##}%%[[:space:]]##}")
# add -- and = to create flags
typeset -a flags
for key val in "${(@kv)parms}"; do
flags =("--${key}='${val}'")
done
# replace the value on the command line
compadd -QU -- "$flags"
}
# add the function as a completion and map it to ctrl-y
compdef -k _yamlExpand expand-or-complete '^Y'
在zshshell 提示符下,輸入命令和 yaml 檔案名:
% print -l -- ./bar.yaml▃
將游標緊跟在 yaml 檔案名之后,點擊ctrl y。yaml 檔案名將替換為擴展引數:
% print -l -- --bar1='1' --bar2='2' ▃
現在你已經準備好了;您可以按 Enter 鍵或添加引數,就像任何其他命令列一樣。
筆記:
- 這僅支持
yaml您的示例中的子集。 - 您可以
yaml向函式添加更多決議,可能使用yq. - 在這個版本中,游標必須在
yaml檔案名旁邊- 否則最后一個值words將為空。您可以添加代碼來檢測這種情況,然后words使用compset -n. compadd并compset在zshcompwid手冊頁中進行了描述。zshcompsys有詳細資訊compdef;關于自動加載檔案的部分描述了另一種部署此類內容的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/334798.html
下一篇:獲取陣列元素并洗掉
