Split the string into 3 separate arguments using xargs
If I have the following:
$ printf '%s\n' "${fa[@]}"
1 2 3
4 5 6
7 8 9
where each line represents a new element in the array. I want to be able to split an element by space separator and use the result as 3 separate parameters and a pipe in xargs.
For example, the first element:
1 2 3
where with xargs I want to pass 1
, 2
and 3
to a simple echo command such as:
$ echo $0
1
4
7
$ echo $1
2
5
8
$ echo $2
3
9
6
So, I'm trying to do it like this:
printf '%s\n' "${fa[@]}" | cut -d' ' -f1,2,3 | xargs -d' ' -n 3 bash -c 'echo $0'
which gives:
1
2
3 4
5
6 7
8
9 10
which besides the strange ordering of the lines - trying xargs -d' ' -n 3 bash -c 'echo $0'
not to print the first "element" of each line ie
$ echo $0
1
4
7
but prints them all out.
What I'm asking, for each element, is how to split the string into three separate arguments that can be referenced via xargs?
Thank!
source to share
You were going in the right direction
Declare an array:
fa=('1 2 3' '4 5 6' '7 8 9')
To achieve what you want:
printf '%s\n' "${fa[@]}" | xargs -n 3 sh -c 'echo call_my_command --arg1="$1" --arg2="$2" --arg3="$3"' argv0
this will display the following lines (change command which is passed to xargs accordingly)
call_my_command --arg1=1 --arg2=2 --arg3=3
call_my_command --arg1=4 --arg2=5 --arg3=6
call_my_command --arg1=7 --arg2=8 --arg3=9
If I just add my answer and change it a bit, we get the following
printf '%s\n' "${fa[@]}" | cut -d' ' -f1,2,3 | xargs -n 3 bash -c 'echo $0 $1 $2'
notice missing -d '' in xargs, this option is not available in some versions of xargs.
source to share