파이프를 통해 여러 인수 전달

파이프를 통해 여러 인수 전달

다음 형식의 무한한 줄을 출력하는 명령이 있습니다.

$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합리적인 것으로 설정되었다고 가정하면 쉘 코드 자갈 심은 다음과 같이 보일 수 있습니다.

#!/bin/sh
IFS=" "
while read word andtherest; do
    $cmd2 --argword="$word" --argtext="$andtherest"
done

andtherest남은 필드는 동작 방식에 따라 모두 하나로 묶어야 하기 때문입니다 read.

답변2

조금 이상한 것을 시도해보세요:

/usr/bin/awk -f
{
    cmd=$1;
    gsub($1 " +", "")
    printf("%s --argword=%s --argtext=\"%s\"\n", cmd2, cmd, $0)
}

해당 출력은 awk 변수를 이름으로 허용합니다.cmd2.

다음 방법으로 테스트할 수 있습니다.

$ 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"

관련 정보