Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

linux - How to return specific text from a file based on its pattern?

I have a file with several lines and would like to output a single word from it. e.g.

bla bla bla bla
WORD1 bla ldskjf sldfkj 0xksjdflksjflksjf

From this file, I would like to output only the word 0xksjdflksjflksjf. I am thinking of a command that would look for the line starting by WORD1 and then, looking for a word starting by 0x in this line.

I'm quite sure that awk or sed would allow me to do that. I found a way to do it but it doesn't very "clean":

awk '/^WORD1/ {print $5}'

It works but is there a better (e.g. based on the word pattern instead of its place in the line) way to do it?

question from:https://stackoverflow.com/questions/65943343/how-to-return-specific-text-from-a-file-based-on-its-pattern

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have a file called 0x.txt with the following:

bla bla bla bla
WORD1 bla ldskjf sldfkj 0xksjdflksjflksjf
bla bla bla bla
WORD1 bla 0xksjdflksjflks ldskjf sldfkj

then:

awk '/^WORD1/ {for (i=1;i<=NF;i++) if ( match($i, /^0x/) ) print $i}' 0x.txt

will print what you need not depending on column number:

0xksjdflksjflksjf
0xksjdflksjflks

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...