简体   繁体   English

文件每一行的Shell命令

[英]Shell command on each line of file

I am trying to write a Perl script which will do the following: 我正在尝试编写一个Perl脚本,它将执行以下操作:
1. Open a file which, in each line, contains the location of multiple files (Say File A, file B) 1.打开一个文件,该文件的每一行包含多个文件的位置(说文件A,文件B)
2. Do an egrep on each of these files something like egrep "module|input|output" 2.对每个文件执行一个egrep,例如egrep“ module | input | output”
3. Store the output of the egrep with the same file name A, B etc but in a different directory) 3.将egrep的输出以相同的文件名A,B等存储,但存储在不同的目录中)

There are more constraints on the egrep, but I can add them later. egrep上还有更多限制,但我可以稍后添加。

My question is how do I do steps 2 and 3? 我的问题是如何执行步骤2和3? Where in, I execute a shell command on each line of my file which is opened by my Perl script. 在其中的位置,我在由Perl脚本打开的文件的每一行上执行shell命令。 And the file location would be, for example, design/rtl/name.v and I want the result of egrep to be stored in design/fake/name.v 文件位置为例如design/rtl/name.v ,我希望将egrep的结果存储在design/fake/name.v

In shell (bash) make a directory results and list your files one to a line in the file "list" and then just type this straight in at the bash prompt 在shell(bash)中生成目录结果,并将文件一一列出到文件“列表”中的一行,然后直接在bash提示符下键入

for i in `cat list`;do egrep "string" $i > result/grep${i}; done

Here is similar in perl. 这与perl类似。 The error behaviour is nicer, it might be a tiny bit faster: the real advantage would be that extra behaviours could be added easier. 错误行为会更好,可能会快一点:真正的好处是可以轻松添加额外的行为。 Save it as a file and run as "perl script list foo" where script is the filename of the script, list is the filename of the list of files and foo is the pattern being searched for 将其另存为文件并以“ perl script list foo”运行,其中script是脚本的文件名,list是文件列表的文件名,foo是要搜索的模式

#!/usr/bin/perl
#

my ( $file, $pattern ) = @ARGV;

open( my $fh, $file ) || "die $! $file\n";

while (<$fh>) {
    chomp;    #trim newline from filename
    my $togrep = $_;
    open( my $grepfh, $togrep ) || warn "$togrep $!";
    if ($grepfh) {
        open( my $output, ">result/$togrep" ) || die "$togrep $!";
        while ( grep( $pattern, <$grepfh> ) ) {
            print $output $_;
        }
    }
}

Loop over the filenames like this: 像这样循环遍历文件名:

while read file
do
   egrep "module|imput|ouput" "$file" > "/another/directory/${file##*/}" 
done < fileList.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM