Ray
Ray

Reputation: 15

Concatenate "string" and "strings sequence separated with spaces"

How can I concatenate stdin with spaces to a string, like this?

echo 'input1 input2 input3' | COMMAND 'inputs='

and get

inputs=input1 input2 input3

This question is similar to How to concatenate stdin and a string? , but multiple inputs are separated with spaces and the number of inputs is arbitrary.

Upvotes: 0

Views: 598

Answers (3)

John Kugelman
John Kugelman

Reputation: 361917

concat() {
    printf '%s' "$1"
    cat
}

or

concat() {
    echo "$1$(cat)"
}

The second one is shorter but involves making a (possibly huge) in-memory string from the input, whilst the first doesn't, and therefore scales much better.

Upvotes: 2

Léa Gris
Léa Gris

Reputation: 19625

If you want to have the space delimited fields from the input stream, handled as distinct arguments to COMMAND, then use bash's read -a to read $IFS delimited fields into an array:

echo 'input1 input2 input3' | {
  read -ra inputs
  COMMAND 'inputs=' "${inputs[@]}"
}

Upvotes: 3

KamilCuk
KamilCuk

Reputation: 141533

You could output your stuff and then output the input.

echo 'input1 input2 input3' | { printf 'inputs='; cat; }

Upvotes: 3

Related Questions