How to concatenate grep results?

hi,

let's say we have input in files test1.txt, test2.txt, text3.txt ... ... ... ('...' means more files & lines not just 'dots')
test1.txt has:

A
B
C
D
...
...
...

test2.txt has

A
B
C
D
...
...
...
and so on.

i would like the output to be:

A B C D ... ... ...

i noticed that doing:

tst1=`grep 'A' *"test"* | grep 'B' *"test"* | grep 'C' *"test"* | grep 'D' *"test"* | ...more greps`
echo "$tst1"

returns the 1st grep but the rest are overwritten by the last grep.

your help will be really appreciated.

In general, when using grep in a pipeline, you need to specify the files only with the first grep, the other greps in the pipeline use stdin as input, not file(s), so:

tst1=$(grep 'A' *"test"* | grep 'B' | grep 'C' | grep 'D' | ...more greps)

You can try to print out on one line by leaving out the quotes:

echo $tst1

which depending on the input may be good enough.

---
But this will not produce what you want. In order to do that you need to specify what you want to accomplish? Do you want to print what these files have in common? It is not clear what the criteria are or what you are trying to accomplish..
---

thanks Scrutinizer. you are correct, it doesn't return anything.

what if i want to grep only 4 lines and put them all in one line? is it possible?

You mean something like this?

echo $(grep -E 'A|B|C|D' *"test"*)

---
On Solaris use /usr/xpg4/bin/grep

1 Like

You may want to check man grep if it has