如何在每行前打印文件名?
我有几个文件,比如说a、b、c,我想要做的事情是:
> cat a b c
在文件a的每一行前面加上"a,",在文件b的每一行前面加上"b,",在文件c的每一行前面加上"c,"。
我可以用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()
但我更想在命令行里完成这个,使用一些简单的命令和管道符号|。
有没有简单的方法可以做到这一点呢?
谢谢。
3 个回答
4
你也可以使用 awk(1)
这个程序哦 :)
$ awk 'BEGIN { OFS=","; } {print FILENAME , $0;}' *
a,hello
b,
b,
b,world
c,from space
d,,flubber
5
grep(1)
和sed(1)
可以帮你完成这个任务: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
8
perl -pe 'print "$ARGV,"' a b c
会做到的。