返回列表 发帖

sed -n "/str1/,/str2/p" file 到底是什么意思?(附例)

本帖最后由 踏沙行 于 2018-9-4 08:27 编辑

已知1.txt内容如下:
1:basktop at time to door
2:basktop at time to floor
3:bathome is webbbs
4:you can not do it
5:yes you need to watch the game
6:he is write for bat
7:he is write for bat
8:you can not do itCOPY
命令:
sed -n /at/,/is/p 1.txt
或者 sed -n "/at/,/is/p" 1.txt
结果都如下:
1:basktop at time to door
2:basktop at time to floor
3:bathome is webbbs
5:yes you need to watch the game
6:he is write for bat1
7:he is write for bat2
8:you can not do it2COPY
请问,这个第8行为什么会被匹配?
附:使用环境 —— win7 64bit,sed版本:sed (GNU sed) 4.4,论坛第三方专区提供的版本(单行版)

回复 2# ai20110304
谢谢楼上两位大神指导。
那么,当我想匹配以下目标时,用sed怎么实现呢?
1、从包含str1的行开始,到包含str2的行结束
2、匹配包含str1或str2的行

TOP

本帖最后由 踏沙行 于 2018-9-4 16:17 编辑

回复 7# ai20110304
谢谢,谢谢@batcher

七楼第一条命令,能讲讲是什么意思吗?
另外,这种使用方法有一个坑,比如改成
set -n "/is/,/at/p;/at/q" 1.txt
输入结果为空,原因是“at”和“is”都在第一行,结果/at/q即直接关闭输出,把匹配第一条pattern的行输出也关闭了。

那么,能不能在第1个分号后,跳转到下一行开始执行呢?sed中有个n指令,是跳到下一行执行。但是不知道在这个语句中,怎么写才能实现该效果
sed "/abc/{n;d}" 1.txt:将1.txt中包含"abc"的下一行删除
sed "/abc/{n;s/ef/fe/g}" 1.txt:将1.txt中包含”abc”的下一行中的"ef"全部替换为"fe"COPY
请问上一句set -n "/is/,/at/p;/at/q" 1.txt,怎么改可以实现如上效果?

TOP

回复 9# Batcher
H:\>sed -n "/at/{:a;N;/is/{/at.*\n.*is/p;d};ba}" 1.txt
1:basktop at time to door
2:basktop at time to floor
3:bathome is webbbs
5:yes you need to watch the game
6:he is write for batCOPY
結果好像还是多了几行啊

TOP

回复 11# Batcher
不好意思,我没有表达清楚:
1、打印,从包含"at"的行,到包含"is"的行,匹配一次即停止打印。若后面还有从“at”到“is"的,不再打印。
2、打印,若只有包含"at"的行,而无包括"is"的行,则只打印含at的行

TOP

回复 13# Batcher
谢谢,能讲讲a N ba指令是什么意思吗?
网上对N的介绍看不明白,另外,没有看到a b这两个指令的使用说明

TOP

本帖最后由 踏沙行 于 2018-9-10 11:09 编辑

回复 15# Batcher
sedsed调试一文所介绍的例子,来自于网页,但是网页挂了,不知道怎么调试了。

我自己的高度方案,结果不正确。
附:我自己的调试方案:
1、H:\a.txt内容为:
1
2
3
4
5COPY
2、从这里下载了sedsed1.0(http://aurelio.net/projects/sedsed/sedsed-1.0),将后缀改为.py,然后执行如下内容,结果出错
H:\>python sedsed.py -d --hide=hold "n;d" b.txt
  File "sedsed.py", line 96
    """
      ^
SyntaxError: invalid syntaxCOPY
【注】我的python版本:Python 3.6.0;操作系统:win7 64位

TOP

回复 18# Batcher
下载了论坛提供的sedsed.zip,解压后和目标文档放在同一目录,操作结果如下:
H:\>dir *.py
驱动器 H 中的卷没有标签。
卷的序列号是 893B-2135
H:\ 的目录
2015-05-11,周一  16:00            52,851 sedsed.py
               1 个文件         52,851 字节
               0 个目录 262,617,034,752 可用字节
H:\>
H:\>type b.txt
1
2
3
4
5
H:\>
H:\>python sedsed.py -d --hide=hold "n;d" b.txt
  File "sedsed.py", line 96
    """
      ^
SyntaxError: invalid syntaxCOPY
不知道错在哪里了?

TOP

好的,谢谢

TOP

返回列表