Unix命令在文件中查找字符串并仅打印带有该字符串的模式文本

Unix command to find a string in a file and print only the pattern text with the string

如果模式具有使用 unix 命令的特定字符串,我只想打印匹配模式。

例如:在xyz.txt文件中找到25487,将xyz.txt文件中pleasetill here之间的文本打印到新文件中文件。

xyz.txt 文件...

.........
..
....
...

please print 25487 this
sadf
sdfa
sdfasgda
till here

.....
.........
..

please print 45862 this
qret
ret
ASF
H
till here
.........
..
....
...

最后只打印

please print 25487 this
sadf
sdfa
sdfasgda
till here

你可以使用 grep。

$ grep -oPz '(?s)\bplease\b.*?25487.*?\btill here\b' file
please print 25487 this
sadf
sdfa
sdfasgda
till here

(?s) DOTALL 修饰符,它使正则表达式中的点也匹配换行符。默认情况下点不匹配换行符。

只需使用 grep 中的上下文选项即可获取当前行之后的行。 -A 选项会给你你想要的,只需指定你想要在当前行之后的行数,所以只需执行:

grep -A 4 25487 xyz.txt > newfile.txt

-A 4 将匹配当前匹配行之后的 4 行。如果你想要使用 -B 之前的 4 行,如果你想要在当前行之前和之后使用 -C.

sed可以很轻松地做到这一点。

 sed -n '/25487/, /till here/ p'

测试

$ sed -n '/25487/, /till here/ p' input
please print 25487 this
sadf
sdfa
sdfasgda
till here

它有什么作用?

  • -n 抑制打印模式 space

  • '/25487/, /till here/ 地址范围。选择两个模式之间的所有线并执行以下操作。

    这里选择25487till here

  • 之间的行
  • p 打印模式 space.

一个简单的awk

awk '/25487/,/till here/' xyz.txt
please print 25487 this
sadf
sdfa
sdfasgda
till here

如果您还有其他测试要做,那就更好了:

awk '/25487/{f=1} f; /till here/{f=0}' xyz.txt

或这个

awk '/25487/{f=1} /till here/{f=0;print} f' xyz.txt
sed '/please/,/till here/!d
     H
     /till here/!b
     s/.*//
     x
     /25487/!d
     s/.//p' YourFile
  • 不关心以 please 开始并以 till here 结束的部分的行和循环(转到下一行条目)
  • 存储行
  • 如果不符合till here,循环
  • 清空当前行
  • 与缓冲区内容交换
  • 如果里面没有25847,删除循环
  • 删除第一个字符(一个额外的新行)并打印,然后循环