我有一個命令,可以輸出這種格式的無限行:
$cmd1
word1 text with spaces and so on
word2 another text with spaces and so on
我想將每一行傳遞給另一個命令,以便第一word
行將傳遞給一個參數,文字的其餘部分將傳遞給另一個參數。像這樣:
$cmd2 --argword=word1 --argtext="text with spaces and so on"
$cmd2 --argword=word2 --argtext="another text with spaces and so on"
答案1
假設最終行有一個換行符(否則該行會丟失)並且cmd2
設定為合理的值,shell 程式碼拼湊的墊片可能看起來像這樣
#!/bin/sh
IFS=" "
while read word andtherest; do
$cmd2 --argword="$word" --argtext="$andtherest"
done
因為剩餘的欄位應該全部集中到andtherest
每個行為方式read
。
答案2
試試一下 awk:
/usr/bin/awk -f
{
cmd=$1;
gsub($1 " +", "")
printf("%s --argword=%s --argtext=\"%s\"\n", cmd2, cmd, $0)
}
此輸出接受 awk 變數作為名稱指令2。
你可以這樣測試:
$ echo "word1 text with spaces and so on" |
awk -v cmd2=foo '{ cmd=$1; gsub($1 " +", ""); printf("%s --argword=%s --argtext=\"%s\"\n", cmd2, cmd, $0) }'
foo --argword=word1 --argtext="text with spaces and so on"