是Shell脚本的新手,需要您的帮助,找到一种方法来搜索模式,并使用SED"删除第二次出现模式后的下一行。我能够在搜索模式之后删除该行(从第一次出现),但我的要求是在第二次出现后删除空行。
sed -re "s/^([^^L])/ \1/" -e "s/^^L/1/" -e "/$esc_filename/{p;s/$esc_filename/"${new_filename}"/}" -e "/^"$new_filename"/{n;d}" "$i" >> "$source_dir/${cap_new_rep_id}.TXT"
OR
sed -re "s/^([^^L])/ \1/" -e "s/^^L/1/" -e "/^ $esc_filename/{p;s/$esc_filename .*/"${cap_new_rep_id}"/}" -e "/"${cap_new_rep_id}"/{N;s/\n.*//;}" "$i" >> "$source_dir/${cap_new_rep_id}.TXT"
上面的命令会搜索Control-L,如果找到,则用空的空格替换1 else并再次搜索字符串并替换为另一个字符串,最后搜索最新的字符串,然后删除下一行但是我只需要在找到第二个模式后删除下一行的选项。
如果任何人能够为实现这一点而投入一些光线,那将是很棒的。
感谢您的帮助。
答案 0 :(得分:0)
请考虑使用awk
:
awk -v first=1 '
!ignore { print } # unless the line is ignored, print it
ignore { ignore = 0 } # if it was ignored, reset ignore flag
/pattern/ {
if(!first) { ignore = 1 } # set ignore bit it pattern is found and it is not the first time
first = 0 # since the pattern has been found, it is not the first time after this.
}' foo.txt
转换此文件:
0
pattern
1
2
3
pattern
4
pattern
6
7
进入这个:
0
pattern
1
2
3
pattern
pattern
7
只需用您的模式替换模式,应该是它。此外,与sed相比,查看正在发生的事情要容易得多。
编辑:我不应该尝试在带有单引号的shell脚本字符串的注释中使用'
。那太傻了。
附录:由于OP在评论中提到,除了第一次出现模式之外,删除第N行的一种方法是使用忽略计数器而不是标志:
# adjust N as necessary
awk -v first=1 -v ignore=0 -v N=2 '
ignore != 1 { print }
ignore != 0 { ignore -= 1 }
/pattern/ {
if(!first) { ignore = N }
first = 0
}' foo.txt
...我相信这是我留下awk tutorial链接的地方。
答案 1 :(得分:0)
sed '0,/pattern/!{/pattern/{N
s/\n.*//g}}'
示例包含以下
的文件hello world
I DON'T want to delete this line since the first pattern is above
world
I want to delete this line
my name is John
my name is Joe
world
I want to delete this line
My name is Jack
this is world
I want to delete this line
rule
在这种情况下,让我们考虑模式为world
sed '0,/world/!{/world/{N
s/\n.*//g}}' my_file
输出
hello world
I DON'T want to delete this line since the first pattern is above
world
my name is John
my name is Joe
world
My name is Jack
this is world
rule