-1

In poking about with xargs, as here:

nicholas@gondor:~/x$ 
nicholas@gondor:~/x$ xargs echo < list.txt
1 2 3
nicholas@gondor:~/x$ 
nicholas@gondor:~/x$ cat list.txt

1 2 3

nicholas@gondor:~/x$

how would xargs give output like:

number is 1
number is 2
number is 3

rather than just the numbers as is currently the result?

I tried using the $ symbol with echo, but wasn't getting the correct output.

also tried:

nicholas@gondor:~/x$ 
nicholas@gondor:~/x$ printf '%s\n' "${list.txt[@]}" | xargs
bash: ${list.txt[@]}: bad substitution

nicholas@gondor:~/x$

but that's apparently not reading in the file correctly.

Would prefer to use echo over printf unless it's overly awkward.

another attempt:

nicholas@gondor:~/x$ 
nicholas@gondor:~/x$ xargs echo 'numbers are ${}' < list.txt
numbers are ${} 1 2 3
nicholas@gondor:~/x$ 

but not sure how to get each number above on a separate line.

see also:

Printing an array to a file with each element of the array in a new line in bash

echo list / array to xargs

  • there are dozens, if not hundreds, of bash tutorials on the net. i suggest you go through one or more them - completing the exercises as you go - and gain a basic understanding of shell scripting. your recent questions suggest you lack that fundamental understanding. https://duckduckgo.com/?q=bash+tutorial – cas Jul 19 '21 at 08:46

1 Answers1

1
$ xargs printf 'Number is %d\n' <file
Number is 1
Number is 2
Number is 3

This reads words from your file and calls the given utility with as many words as possible at a time. The printf utility will reuse its format string for each set of arguments.

The above would end up executing

printf 'Number is %d\n' 1 2 3

If you have spaces or tabs on the lines in your file:

$ cat file
1 2
3 4
5 6
$ xargs printf 'Number is %s\n' <file
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6

The above is the result of running the printf utility with each whitespace-delimited word from you file, i.e.,

printf 'Number is %s\n' 1 2 3 4 5 6
$ xargs -I {} printf 'Number is %s\n' {} <file
Number is 1 2
Number is 3 4
Number is 5 6

The above runs printf three times, each with a separate line from your file. Each {} in the utility's argument list will be replaced by a line read from your file.

If you file contains quoted strings:

'1 2'
'3 4'
'5 6'

Then:

$ xargs printf 'Number is %s\n' <file
Number is 1 2
Number is 3 4
Number is 5 6

The above is the result of running the equivalent of

printf 'Number is %s\n' '1 2' '3 4' '5 6'
Kusalananda
  • 333,661