简体   繁体   English

从文件中删除所有行,以特定字符串开头和结尾

[英]Remove all lines from a file, starting and ending with a specific string

I need to check if a file contains a specific two strings and if it does, remove all the text between them (strings included).我需要检查文件是否包含特定的两个字符串,如果包含,请删除它们之间的所有文本(包括字符串)。 Let's say I have a file text which looks something like this:假设我有一个看起来像这样的文件text

line of text
line of text
line of text
line of text
#1st string
line of text
line of text
line of text
#2nd string

Now I would like to delete all the lines between #1st string and #2nd string and those two strings included.现在我想删除#1st string#2nd string之间的所有行以及这两个字符串。

I tried getting the whole text into a variable and then removing them like that:我尝试将整个文本放入一个变量中,然后像这样删除它们:

prefix="#1st string"
suffix="#2nd string"

#content of a file into variable
tempfile=$( cat text )
tempfile=${tempfile#"$prefix"}
tempfile=${tempfile%"$suffix"}
echo ${tempfile}

Unfortunately, this doesn't work because the text file contains some commands which somehow list the content of the current directory and blend the output into the variable which leaves the file corrupted.不幸的是,这不起作用,因为文本文件包含一些命令,这些命令以某种方式列出当前目录的内容并将 output 混合到使文件损坏的变量中。 Can I prevent that somehow, or is there a better way of achieving this altogether?我可以以某种方式阻止这种情况,还是有更好的方法来完全实现这一点?

You could use sed to remove the line range:您可以使用 sed 删除行范围:

sed '/#1st string/,/#2nd string/d' text

To store the result in-place, use要就地存储结果,请使用

sed -i '/#1st string/,/#2nd string/d' text

or the more portable或更便携

sed '/#1st string/,/#2nd string/d' text > tempfile && mv tempfile text

And finally, because you might have files where only the first string exists, you have to check existence of the second string first:最后,因为您可能有只存在第一个字符串的文件,所以您必须首先检查第二个字符串是否存在:

grep -q '#2nd string' text && sed '/#1st string/,/#2nd string/d' text

You could use grep's before and after feature:您可以使用 grep 的前后功能:

prefix="#1st string"
suffix="#2nd string"

grep -B 100000000 $prefix text | grep -v $prefix > output
grep -A 100000000 $suffix text | grep -v $suffix >> output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM