问题
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 theif
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