-1

I cannot find an easy solution for this problem in bash.

I have several files: aaa.txt / bbb.txt / ccc.txt

The content of each file is:

aaa.txt

    1234
    1234
    1234

bbb.txt

    5678
    5678
    5678

ccc.txt

    10
    20
    30
    40

I need to add the name of the file to the beginning of each line using a loop.

There are about 300 files and I want to concatenate all of them in one file to do a grep instead of looking file by file, and the reason to add the name of the file is to do that grep. This should be the result:

aaa.txt

    aaa: 1234
    aaa: 1234
    aaa: 1234

bbb.txt

    bbb: 5678
    bbb: 5678
    bbb: 5678

ccc.txt

    ccc: 10
    ccc: 20
    ccc: 30
    ccc: 40

Could you help me?

If there is any doubt just ask for it

Thanks!

Jorge
  • 1
  • 2
    ```grep -e ".*" * > result``` and grep will add the file name at the beginning of the line. But then you can grep immediately too, probably – Ronald Jun 28 '18 at 14:13
  • 3
    You could use `grep -H` to force grep results with the filename. You don't discuss *how* you are currently using grep, but I think this may help: if you're doing something like `for file in *; do grep "$pattern" "$file"; done > result`, then throw `-H` in there to get the filename in the result file. – glenn jackman Jun 28 '18 at 14:25

2 Answers2

0

Use the -H option, which prefixes the file name for every line searched. ^ matches the beginning of every line:

grep -H ^ *.txt > bigfile.txt

Note that doing this:

grep -H ^ *.txt > bigfile.txt
grep searchstring bigfile.txt

...can be simplified to this:

grep -H searchstring *.txt

...which is also about twice as efficient.

agc
  • 7,973
  • 2
  • 29
  • 50
0

Yep, what agc said is the one that worked:

cd /some/path/ && grep -H ^ *.txt > /some/path/bigfile.txt

Thanks everyone!

Jorge
  • 1