Home > Blockchain >  xargs split string by space
xargs split string by space

Time:05-13

I have the following shell script:

serial_numbers=$(ddcutil detect | grep "Serial number" | awk '{print $3}' | uniq)
echo $serial_numbers | xargs -P $(echo $serial_numbers | wc -w) -I % ddcutil setvcp 10 100 --sn %

The variable $serial_number contains the string '8TRNJQ2 FGVF2Y2'. xargs interprets this string as one single argument and produces only one invocation of ddcutil setvcp. But I want xargsto split the string at the space, so iÍ get two invocations with 8TRNJQ2 and FGVF2Y2 as arguments.

Edit: using -t ' ' gives me strange results for the last part in the string: 'FGVF2Y2'$'\n'

CodePudding user response:

xargs works fine if you pipe it directly from a command, but not if you echo the result of the same command output.

Add this transformation in your command:

#!/bin/bash

echo $serial_numbers | tr ' ' '\n' | xargs -P $(echo $serial_numbers | wc -w) -I % ddcutil setvcp 10 100 --sn %

xargs will now understand that you want to split on your serial numbers.

Alternatively, you could put the tr in your first line and store the separated serial numbers in the variable.

  • Related