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 pre开发者_运维知识库fer to do it in the command line, combining some simple commands with the pipe | operator.
Is there a easy way of accomplishing this?
Thanks.
perl -pe 'print "$ARGV,"' a b c
will do it.
grep(1)
and sed(1)
can do this 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
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
精彩评论