Reputation: 1026
I have the following directory:
> tree
.
├── a.txt
└── b.txt
> ls
a.txt b.txt
When I run command ls | xargs echo
I get the following:
> ls | xargs echo
a.txt b.txt
While I would have expected result to look something along the lines of
> ls | xargs echo
a.txt
b.txt
Given that I am expecting xargs
to process each file separately and echo
to print each input on its own separate line.
Why the difference of expected vs actual?
As suggested I have tried:
find . -mindepth 1 -maxdepth 1 -exec echo {} \;
Which does work as expected and I presume allows other command to be subbed in for echo with -exec
.
However, trying the other suggestions to try to get xargs working still does not work (prints the output on the same line).
Example:
printf "%s\n" * | xargs
a.txt b.txt
> find . -mindepth 1 -maxdepth 1 | xargs echo
./b.txt ./a.txt
Upvotes: 3
Views: 3374
Reputation: 12377
Use find
with -mindepth
and -maxdepth
options like so:
find . -mindepth 1 -maxdepth 1
# or:
find . -mindepth 1 -maxdepth 1 -exec echo {} \;
If you really must parse the output of ls
(not the recommended practice, see the comments), use xargs
with -n1
option:
ls | xargs -n1 echo
Here is how to control which directories find searches, and how it searches them. These two options allow you to process a horizontal slice of a directory tree.
Option:
-maxdepth levels
Descend at most
levels
(a non-negative integer) levels of directories below the command line arguments.
...
Option:-mindepth levels
Do not apply any tests or actions at levels less thanlevels
(a non-negative integer). Using-mindepth 1
means process all files except the command line arguments.
--max-args=max-args
-n max-args
Use at mostmax-args
arguments per command line.
Upvotes: 5