简体   繁体   中英

unix bash - extract a line from file

need your help!!! I tried looking for this but to no avail.

How can I achieve the following using bash?

I've a flat file called "cube.mdl" that contains:

[...]
bla bla bla bla lots of lines above
Cube 8007841 "BILA_" MdcFile "BILA_CO_PM_MKT_BR_CUBE.mdc"
bla bla bla more lines below
[...]

I need to open that file, look for the word "MdcFile" and get the string that follows between quotes, which would be BILA_CO_PM_MKT_BR_CUBE.mdc

I know AWK or grep are powerful enough to do this in one line, but I couldn't find an example that could help me do it on my own.

Thanks in advance! JMA

You can use:

grep -o -P "MdcFile.*" cube.mdl | awk -F\" '{ print $2 }'

This will use grep 's regex to only return MdcFile and everything after it in the current line. Then, awk will use the " as a delimiter and print only the second word - which would be your "in-quotes" word(s), returned without the quotes of course.

The option -o , --only-matching specifies to return only the text matching that matches and the -P , --perl-regexp specifies that the pattern is a Perl-Regex pattern. It appears that some versions of grep do not contain these options. The OP's version is a version that does not include them, but the following appears to work for him instead:

grep "MdcFile.*" cube.mdl | awk -F\" '{ print $2 }'
grep MdcFile cube.mdl | awk '{print $5}'

假设所有这些位中都没有空格可以抛出位置计数,它将做到这一点。

这可能会做到。

sed -n '/MdcFile / s/.*MdcFile "\(\[^"\]\+\)".*/\1/;/MdcFile / p' INPUTFILE

awk用于整个过程,并以"作为记录分隔符:

awk -v RS='"' '/MdcFile/ { getline; print }' cube.mdl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM