grep比赛前一行加上比赛


8
zzzzzzzzz
aaaaaaaaa
bbbbbbbbb &
ccccccccc &
ddddddddd
hhhhhhhhh
eeeeeeeee
fffffffff &
ggggggggg &

在上面的行中,我想要的是grep/ sed/ awk(任何方法都可以)行上有&符号加一行的符号。因此,例如,所需的输出将如下所示:

aaaaaaaaa
bbbbbbbbb &
ccccccccc &
eeeeeeeee
fffffffff &
ggggggggg &

以下是我没有运气尝试过的。

egrep "&" | -b 1 file.txt

Answers:


16

你可以做:

grep -B 1 '&$' your_file

这将寻找以结尾的行&,将其删除$以匹配行中的&任何地方。

-B开关告诉grep到线那场比赛之前来输出“上下文”线。在这种情况下,由于您需要一行上下文,因此需要-B 1

但是,此开关在GNU中可用,grep但在POSIX标准中不可用。

这是一个简单的sed解决方案,在您没有GNU的情况下应该会有所帮助grep

sed -n '/&/!N;/&/p' your_file

怎么运行的

  • -n开关禁止默认的“打印”操作sed
  • /&/!N表示:如果当前行不包含&,则将下一行追加到模式空间。
  • /&/p表示:匹配&并打印图案空间。

2
@RanaKhan欢迎来到Stack Exchange :)很高兴能为您提供帮助。如果此答案有助于解决您的问题,请不要忘记将此答案标记为已接受(使用答案旁边投票按钮下方的对勾),以便其他浏览该网站的人知道此问题已解决。
Joseph R.

GNU/grep无法提供变体时+1 ,谢谢!
ckujau

3

以下是如何模仿grep -B1sed

sed '$!N;/pattern/P;D' infile

和这里的非常相似。就像另一个一样,它读取N分机行,但是这一次,如果模式空间匹配,它会P漂洗到第一条\newline ,然后像另一条一样,删除到第一条ewline并重新启动循环。因此,使用您的示例输入: D\n

sed '$!N;/&/P;D' infile

输出:

aaaaaaaaa
bbbbbbbbb &
ccccccccc &
eeeeeeeee
fffffffff &
ggggggggg &

同样,要查看其工作原理,请在l之前和之后添加N以查看模式空间::

sed 'l;$!N;l;/&/P;D' infile

例如带有示例文件:

zzzz &
aaaa
bbbb
cccc &
dddd &
hhhh
eeee
ffff &
gggg &

这些是sed执行的命令和相应的输出:

cmd输出cmd
l       zzzz &$               N # read in the next line
l       zzzz &\naaaa$         # pattern space matches so print up to \n
P       zzzz &                D # delete up to \n 
l       aaaa$                 N # read in the next line
l       aaaa\nbbbb$           D # delete up to \n (no match so no P)
l       bbbb$                 N # read in the next line
l       bbbb\ncccc &$         # pattern space matches so print up to \n
P       bbbb                  D # delete up to \n
l       cccc &$               N # read in the next line
l       cccc &\ndddd &$       # pattern space matches so print up to \n
P       cccc &                D # delete up to \n
l       dddd &$               N # read in the next line
l       dddd &\nhhhh$         # pattern space matches so print up to \n
P       dddd &                D # delete up to \n
l       hhhh$                 N # read in the next line
l       hhhh\neeee$           D # delete up to \n (no match so no P)
l       eeee$                 N # read in the next line
l       eeee\nffff &$         # pattern space matches so print up to \n
P       eeee                  D # delete up to \n
l       ffff &$               N # read in the next line
l       ffff &\ngggg &$       # pattern space matches so print up to \n
P       ffff &                D # delete up to \n
l       gggg &$               # last line so no N 
l       gggg &$               # pattern space matches so print up to \n
P       gggg &                D # delete up to \n
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.