Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: print each input string in a new line

Tags:

bash

echo

newline

With xargs, I give echo several strings to print. Is there any way to display each given string in a new line?

find . something -print0 | xargs -r0 echo

I'm sure this is super simple, but I can't find the right key words to google it, apparently.

like image 990
Ricky Robinson Avatar asked Jun 19 '13 16:06

Ricky Robinson


2 Answers

Here's one way with echo to get what you want.

find . something -print0 | xargs -r0 -n1 echo

-n1 tells xargs to consume 1 command line argument with each invocation of the command (in this case, echo)

like image 97
doubleDown Avatar answered Sep 19 '22 06:09

doubleDown


find . something -print0 | xargs -r0 printf "%s\n"

Clearly, find can also print one per line happily without help from xargs, but presumably this is only part of what you're after. The -r option makes sense; it doesn't run the printf command if there's nothing to print, which is a useful and sensible extension in GNU xargs compared with POSIX xargs which always requires the command to be run at least once. (The -print0 option to find and the -0 option to xargs are also GNU extensions compared with POSIX.)

Most frequently these days, you don't need to use xargs with find because POSIX find supports the + operand in place of the legacy ; to -exec, which means you can write:

find . something -exec printf '%s\n' {} +

When the + is used, find collects as many arguments as will fit conveniently on a command line and invokes the command with those arguments. In this case, there isn't much point to using printf (or echo), but in general, this handles the arguments correctly, one argument per file name, even if the file name contains blanks, tabs, newlines, and other awkward characters.

like image 36
Jonathan Leffler Avatar answered Sep 22 '22 06:09

Jonathan Leffler