In this answer, I'm addressing two different scenarios:
- You want to match the filename that contains both
a
and b
in the current directory and then you want to do something to these files.
- You want to process the output of your two
echo
commands to remove the newlines.
If you want to loop over the filenames, then it would be good to have a single pattern that matches all names and then uses the expansion of that pattern in a loop. Using echo
would not be advisable as this removes the distinction between individual filenames.
In the zsh
shell, the single pattern (*a*b*|*b*a*)
would expand to all names where the letters a
and b
occur in any order.
In the bash
shell, you could use the single extended globbing pattern (or ksh
-like globbing pattern) @(*a*b*|*b*a*)
to do the same thing. The bash
shell does not enable extended globbing patterns by default, so you would need to enable these with shopt -s extglob
first.
In the bash
shell, therefore, you could use something like
shopt -s extglob
for name in @(ab|ba); do
# process "$name" here
done
Another way to generate the wanted filenames for processing is by using find
:
find . ! -name . -prune -name '*a*' -name '*b*'
This looks in the current directory (only) for any name that contains both a
and b
. You would then call some other utility using -exec
at the end of this command to perform the operation, for example with
find . ! -name . -prune -name '*a*' -name '*b*' -exec sh -c '
for name do
# process "$name" here
done' sh {} +
Here, find
generates the filenames used by the in-line sh -c
script. See also Understanding the -exec option of `find`
However, if this is a text-processing exercise and the purpose is to arrange two or more lines of text (the output from your two echo
invocations) into a single line, then you'd do this by piping the text through paste -s -
. This would additionally remove any newlines embedded in filenames. Using paste
in this way rather than tr -d '\n'
(which also removes newlines) ensures that the resulting text is terminated by a single newline at the end.