开发者

How do i print word after regex but not a similar word?

开发者 https://www.devze.com 2023-01-15 23:10 出处:网络
I want an awk or sed command to print the word after regexp. I want to find the WORD after a WORD but not the WORD that looks similar.

I want an awk or sed command to print the word after regexp.

I want to find the WORD after a WORD but not the WORD that looks similar.

The file looks like this:

 somethingsomething
 X-Windows-Icon=xournal
 somethingsomething
 Icon=xournal
 somethingsomething
 somethingsomething 

I want "xournal" from the one that say "Icon=xournal". This is how far i have come until now. I have tried an AWK string too but it was also unsuccessful.

cat "${开发者_如何学Pythonfile}" | grep 'Icon=' | sed 's/.*Icon=//' >> /tmp/text.txt

But i get both so the text file gives two xournal which i don't want.


Use ^ to anchor the pattern at the beginning of the line. And you can even do the grepping directly within sed:

sed -n '/^Icon=/ { s/.*=//; p; }' "$file" >> /tmp/text.txt

You could also use awk, which I think reads a little better. Using = as the field separator, if field 1 is Icon then print field 2:

awk -F= '$1=="Icon" {print $2}' "$file" >> /tmp/text.txt


This might be useful even though Perl is not one of the tags. In case if you are interested in Perl this small program will do the task for you:

#!/usr/bin/perl -w

while(<>)
{
    if(/Icon\=/i)
    {
        print $';
    }
}

This is the output:

C:\Documents and Settings\Administrator>io.pl new2.txt
xournal
xournal

explanation:

  • while (<>) takes the input data from the file given as an argument on the command line while executing.
  • (/Icon\=/i) is the regex used in the if condition.
  • $' will print the part of the line after the regex.


All you need is:

sed -n 's/^Icon=//p' file
0

精彩评论

暂无评论...
验证码 换一张
取 消