How to print the contents of a file with a file name before each line?

I have some files, say a, b, c, I would like something like

 > cat a b c

but with "a" at the beginning of line a. "b" at the beginning of lines b and "c" at the beginning of lines c. I can do it with python:

#!/bin/env python

files = 'a b c'

all_lines = []
for f in files.split():
  lines = open(f, 'r').readlines()
  for line in lines:
    all_lines.append(f + ',' + line.strip())

fout = open('out.csv', 'w')
fout.write('\n'.join(all_lines))
fout.close()

but I would prefer to do this on the command line by combining some simple commands with the channel | Operator.

Is there an easy way to do this?

Thank.

+5
source share
3 answers
perl -pe 'print "$ARGV,"' a b c

will do it.

+8
source

grep(1)and sed(1)can do it for you grep -H '' <files> | sed 's/:/,/'::

$ cat a ; cat b ; cat c
hello


world
from space
$ grep -H '' * | sed 's/:/,/'
a,hello
b,
b,
b,world
c,from space
+5
source

awk(1):)

$ awk 'BEGIN { OFS=","; } {print FILENAME , $0;}' *
a,hello
b,
b,
b,world
c,from space
d,,flubber
+4

All Articles