字符串从文件中提取

时间:2014-09-03 20:35:29

标签: bash grep

我有一个包含以下行的文件:

Aug 25 11:20:19   master set to 'John Jacob' (ID 12345) based on [Created Date] = '2014-05-30 20:58:59'
Aug 25 11:20:19  some text
Aug 25 11:20:49   master set to 'Jane Joy' (ID 6789) based on [Created Date] = '2014-05-30 20:59:07'
Aug 25 11:20:19 more text
Aug 25 11:20:19  more text ("ID not found")
Aug 25 11:20:19  master is even more text ("ID Not found") but alternate ID (ID 11358) exists"

我试图提取以" master"开头的字符串。直到")" (ID 12345)。

这就是我想要做的事情:

grep "master set to" | cut -d ")" -f input.txt

但是当我运行它时,文本文件中的所有内容都会返回。我使用grep和cut是否正确?

提前致谢, 西马克

4 个答案:

答案 0 :(得分:2)

使用GNU Grep' --only-matching标志

$ grep --only-matching 'master.*)' input.txt 
master set to 'John Jacob' (ID 12345)
master set to 'Jane Joy' (ID 6789)
master is even more text ("ID Not found") but alternate ID (ID 11358)

答案 1 :(得分:0)

你的专栏应该是

grep "master set to" input.txt | cut -d ")" -f 1

但请注意,它会删除尾随)并将日期保留在开头。

$ grep "master set to" input.txt | cut -d")" -f1
Aug 25 11:20:19   master set to 'John Jacob' (ID 12345
Aug 25 11:20:49   master set to 'Jane Joy' (ID 6789

请参阅@ Codegnome的答案,了解使用grep

的更好方法

答案 2 :(得分:0)

您可以尝试使用grep

的正则表达式

grep 'master.+\)' inputfile.txt > outputfile.txt

答案 3 :(得分:0)

awk可能会:

awk -F"master " 'NF>1 {split($2,a,")");print a[1]")"}' file
set to 'John Jacob' (ID 12345)
set to 'Jane Joy' (ID 6789)
is even more text ("ID Not found")