パイプを通して複数の引数を渡す

パイプを通して複数の引数を渡す

この形式の無限行を出力するコマンドがあります:

$cmd1
word1 text with spaces and so on
word2 another text with spaces and so on

word最初の行が 1 つの引数に渡され、残りのテキストが別の引数に渡されるように、すべての行を別のコマンドに渡したいと思います。次のようになります。

$cmd2 --argword=word1 --argtext="text with spaces and so on"
$cmd2 --argword=word2 --argtext="another text with spaces and so on"

答え1

最終行に改行があると仮定すると(そうでない場合はその行は失われます)、それがcmd2適切な値に設定されているとすると、シェルコードの寄せ集めのシムは次のようになります。

#!/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"

関連情報