Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print file contents with filename before each line?

I have several files, say, a,b,c, I would like to something like

 > cat a b c

but with "a," in the beginning lines of a. "b," in the beginning of the lines of b and "c," in the beginning of the lines of c. I can do this using 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 it in the command line, combining some simple commands with the pipe | operator.

Is there a easy way of accomplishing this?

Thanks.

like image 432
skeept Avatar asked May 16 '11 22:05

skeept


2 Answers

perl -pe 'print "$ARGV,"' a b c

will do it.

like image 170
cjm Avatar answered Oct 20 '22 17:10

cjm


You can also use the awk(1) program :)

$ awk 'BEGIN { OFS=","; } {print FILENAME , $0;}' *
a,hello
b,
b,
b,world
c,from space
d,,flubber
like image 38
sarnold Avatar answered Oct 20 '22 17:10

sarnold