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

醉酒当歌 提交于 2019-12-24 00:48:40

问题


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 "${file}" | grep 'Icon=' | sed 's/.*Icon=//' >> /tmp/text.txt

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


回答1:


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



回答2:


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.



回答3:


All you need is:

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


来源:https://stackoverflow.com/questions/3672139/how-do-i-print-word-after-regex-but-not-a-similar-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!