3

I have many .txt files with their filenames being different dates:

01.01.2010.txt
02.01.2010.txt
...

Currently each file (e.g.: 01.01.2010.txt) looks like this:

  0.351  XXX  XXX  XXX  XXX
  0.292  XXX  XXX  XXX  XXX  

How do I add the filename to each line of the file and keep the format?

... so it looks like this, for file 01.01.2010.txt:

  01.01.2010  0.341  XXX  XXX  XXX  XXX
  01.01.2010  0.122  XXX  XXX  XXX  XXX  

.. and looks like this, for file 02.01.2010.txt:

  02.01.2010  0.391  XXX  XXX  XXX  XXX
  02.01.2010  1.342  XXX  XXX  XXX  XXX  

These files are stored in subdirectories. If there is a one-liner that can process all of them and also the subdirectories, it would be awesome.

- /patch/to/file
 -/path/to/file/sub1/
 -/path/to/file/sub2/
 -/path/to/file/sub3/
user3200534
  • 392
  • 1
  • 3
  • 10

2 Answers2

3

You can use:

grep -r . .

The first . is RegExp patern matching any character. It will match all lines.

The second . is for the current folder, but you can replace it with any valid path. E.g.:

grep -r . /etc/
Mircea Vutcovici
  • 17,619
  • 4
  • 56
  • 83
2

Suggest using bash loops and sed. For example:

Create a test file set:

$ for i in $(seq -w 1 10); do echo $i-content > $i.txt; done

Assemble the replacment command:

$ for i in *.txt; do sed -i.bak s/^/$(basename $i .txt)\ /g $i; done

Combine it with find:

for i in $(find /your/source/directory/ -iname "*.txt" -print)
do sed -i.bak s/^/$(basename $i .txt)\ /g $i; done

This was not optimized for performance, and is therefore likely not the most efficient way of doing the requested task.

hargut
  • 3,908
  • 7
  • 10