Python 如何在每行之前打印文件名为的文件内容?
我有几个文件,比如,a,b,c,我想Python 如何在每行之前打印文件名为的文件内容?,python,perl,bash,scripting,sed,Python,Perl,Bash,Scripting,Sed,我有几个文件,比如,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 + ','
> 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()
但我更喜欢在命令行中执行,将一些简单的命令与pipe |操作符结合起来
有没有一种简单的方法可以做到这一点
谢谢。grep(1)
和sed(1)
可以为您做到这一点:grep-H'| sed的/:/,/'
:
$ cat a ; cat b ; cat c
hello
world
from space
$ grep -H '' * | sed 's/:/,/'
a,hello
b,
b,
b,world
c,from space
您还可以使用
awk(1)
程序:)
会的。这很聪明,但是如果只有一个文件,你可能想在
grep
中添加一个-H
选项。比grep-H
更便携:grep'/dev/null a b c
@Gilles,非常好的建议,谢谢。不过,很难将其整合到一个简单的示例中,因此,希望将该评论标记为有用,能够充分引起人们的注意。:)为什么不把of设为逗号呢?
$ awk 'BEGIN { OFS=","; } {print FILENAME , $0;}' *
a,hello
b,
b,
b,world
c,from space
d,,flubber
perl -pe 'print "$ARGV,"' a b c