Let the output of a program to be a multiple line text:
$: some_program
↓
line 1
line 2
Now how to use the output so each line is passed as a single argument?
$: count_arguments $(some_program)
↓
4
won't work because it split by new lines and spaces.
count_arguments "$(some_program)"
↓
1
won't work either.
With an intermediary step could the output be read
into an array and then use the array as "${arr[@]}"
But I am looking for a one line solution. Is it possible?
CodePudding user response:
With Bashv4 , mapfile
is one solution.
mapfile -t output < <(some_command); your_command "${output[@]}"
or
echo "${#output[*]}"
Counting the output of some_command, just use wc
some_command | wc -l
CodePudding user response:
You could convert the newlines to NULL characters, and use xargs -0
(the -0
tells it to use NULL as a delimiter, instead of whitespace):
some_program | tr '\n' '\0' | xargs -0 count_arguments
There is one possible caveat, though: if xargs
thinks there are too many lines (arguments) or they're too big, it'll split them into reasonable-sized groups and run the utility separately on each group. OTOH if xargs
thinks that, it's probably right any any method that didn't split them would just straight-up fail.