文件每一行的shell命令

文件每一行的shell命令

本文介绍了文件每一行的shell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 Perl 脚本,它将执行以下操作:
1. 打开一个文件,每行包含多个文件的位置(比如文件 A,文件 B)
2. 对每个文件执行 egrep 类似 egrep "module|input|output"
3. 将 egrep 的输出以相同的文件名 A、B 等存储在不同的目录中)

I am trying to write a Perl script which will do the following:
1. Open a file which, in each line, contains the location of multiple files (Say File A, file B)
2. Do an egrep on each of these files something like egrep "module|input|output"
3. Store the output of the egrep with the same file name A, B etc but in a different directory)

egrep 有更多限制,但我可以稍后添加它们.

There are more constraints on the egrep, but I can add them later.

我的问题是如何进行第 2 步和第 3 步?在哪里,我在我的 Perl 脚本打开的文件的每一行上执行一个 shell 命令.例如,文件位置是 design/rtl/name.v,我希望 egrep 的结果存储在 design/fake/name.v

My question is how do I do steps 2 and 3? Where in, I execute a shell command on each line of my file which is opened by my Perl script. 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

推荐答案

在 shell (bash) 中创建一个目录结果并将您的文件列出到文件list"中的一行,然后直接在 bash 中输入提示

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

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

这里在perl中类似.错误行为更好,它可能更快一点:真正的优势是可以更容易地添加额外的行为.将其另存为文件并以perl script list foo"运行,其中 script 是脚本的文件名,list 是文件列表的文件名,foo 是正在搜索的模式

Here is similar in 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

#!/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 $_;
        }
    }
}

这篇关于文件每一行的shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 12:10