如何通过目录读取特定行并输出到文本文件?

时间:2014-08-10 15:39:29

标签: bash

如何在bash脚本中读取目录,解析每个文件,如foobar_plugin.py,并将''' ''' <描述的行中的所有内容写出来。 / p>

def foobar(self, args):
    '''Backup data to repository.'''

我设想脚本输出类似于 -

command foobar #pulled from the def line above#
write #pulled from between ''' and '''#

# goto next file; repeat#
command next_foobar
write #pulled again#

有13个foobar_plugin.py脚本需要读取,3个脚本名称为foobar_barfoo_plugin.py。并非每个foobar_plugin.py文件都包含def foobar(self, args):,如果没有,则需要处理到下一个插件文件。

每个foobar_plugin.py在'''和'''之间包含不同的描述符,而这些描述符是我想要数据挖掘的。

我怎么能这样做并将所有内容输出到一个文本文件?

2 个答案:

答案 0 :(得分:1)

如果您不关心完全匹配输出格式,可以使用grep:

$ cat file
something else

def foobar(self, args):
    '''Backup data to repository.'''

blah blah blah
$ grep -rB1 "'''.*'''" .
./file-def foobar(self, args):
./file:    '''Backup data to repository.'''

-r用于递归,-B1也用于打印上一行

答案 1 :(得分:1)

要从user000001添加格式化部件,请说明您有以下文件:

$cat file1_plugin.py
something else

def foobar(self, args):
    '''Backup data to repository.'''

$cat file2_plugin.py
blah blah blah

def next_foobar(self, args):
    '''Backup other data'''

用那个awk one-liner:

grep -B1 "'''.*'''" *_plugin.py | 
awk '$1~/def/{printf "command " ; for (i=2;i<NF;i++) printf $i" "; print $NF}
($1~/:/){printf "write " ; for (i=2;i<NF;i++) printf $i" "; print $NF"\n"}'

command foobar(self, args):
write '''Backup data to repository.'''

command next_foobar(self, args):
write '''Backup other data'''

如果你想摆脱单引号:

grep -B1 "'''.*'''" *_plugin.py |
awk -v replace="'" '
($1~/def/){printf "command " ; for (i=2;i<NF;i++) printf $i" "; print $NF}
($1~/:/){printf "write " ; for (i=2;i<NF;i++) {gsub(replace,"",$i); printf $i" "}; gsub(replace,"",$i); print $NF"\n"}'

<强>输出

command foobar(self, args):
write Backup data to repository.

command next_foobar(self, args):
write Backup other data

希望这有帮助