在文件中查找搜索字符串并在同一行中打印下一个单词

时间:2022-01-15 10:02:52

For example, consider a file "abc.txt" has following content:

例如,考虑文件“abc.txt”具有以下内容:

#--------------- Module Id ---------------
MODULE_ID='ACXX'
MODULE_ID='BCXX'
MODULE_ID='CCXX'

Now, I want to search "MODULE_ID" keyword in that file and if found it should print value in that quotes i.e. "1".
Can I know how to do that in Linux?

现在,我想在该文件中搜索“MODULE_ID”关键字,如果发现它应该在该引号中打印值,即“1”。我可以在Linux中知道如何做到这一点吗?

I tried with following but couldn't succeed:

我尝试了以下但无法成功:

grep -o 'MODULE_ID='[^']*'' uk.spec > results.txt

grep -Po 'MODULE_ID="\K.*?(?=")' uk.spec 

perl -ne 'if(m/MODULE_ID="(.*?)"/){ print $1 . "\n"; }'

2 个解决方案

#1


0  

Try this:

open my $fh, "<", "file.txt" or die $!;

while (<$fh>)
{
    chomp;
    if (m/^MODULE_ID='(.*)'/)
    {
        print qq{"$1"}, "\n";
    }
}

____DATA____
MODULE_ID='ACXX'
MODULE_ID='BCXX'
MODULE_ID='CCXX'

Output:

"ACXX"
"BCXX"
"CCXX"

#2


-2  

A simple Perl solution:

一个简单的Perl解决方案:

#/usr/bin/perl -ne
chomp $_; if($_ =~ /MODULE_ID=(.*)/) { print "$1\n"; }

This can be run as a shell one-liner thusly:

这可以作为shell one-liner运行:

perl -ne 'chomp $_; if($_ =~ /MODULE_ID=(.*)/) { print "$1\n"; }' abc.txt

#1


0  

Try this:

open my $fh, "<", "file.txt" or die $!;

while (<$fh>)
{
    chomp;
    if (m/^MODULE_ID='(.*)'/)
    {
        print qq{"$1"}, "\n";
    }
}

____DATA____
MODULE_ID='ACXX'
MODULE_ID='BCXX'
MODULE_ID='CCXX'

Output:

"ACXX"
"BCXX"
"CCXX"

#2


-2  

A simple Perl solution:

一个简单的Perl解决方案:

#/usr/bin/perl -ne
chomp $_; if($_ =~ /MODULE_ID=(.*)/) { print "$1\n"; }

This can be run as a shell one-liner thusly:

这可以作为shell one-liner运行:

perl -ne 'chomp $_; if($_ =~ /MODULE_ID=(.*)/) { print "$1\n"; }' abc.txt