Home > Mobile >  use whitespace as delimiter for xargs arguments
use whitespace as delimiter for xargs arguments

Time:02-01

Is it possible to pass a string with spaces to xargs and use each word as argument?

For example, I am trying something like this. But both word are treated as a single argument.

echo foo bar | xargs -I {} sh -c 'echo item: {}' 

I would like to do it with shell and not with bash. Otherwise, I think arrays might be helpful, but they don't exist in shell.

CodePudding user response:

You could use the -d option to specify the delimiter:

echo 'foo bar' | xargs -I {} -d ' ' sh -c 'echo item: {}'

Will result in:

item: foo
item: bar

--delimiter=delim, -d delim
Input items are terminated by the specified character. The specified delimiter may be a single character, a C-style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible.

  •  Tags:  
  • Related