我有一个文本文件,其中有一行

sometext sometext sometext TEXT_TO_BE_REPLACED sometext sometext sometext

我需要将上面的整行替换为

This line is removed by the admin.

搜索关键字是text_to_be_replace

我需要为此写一个shell脚本。如何使用sed实现这一点?


当前回答

这和上面那个很相似。

sed 's/[A-Za-z0-9]*TEXT_TO_BE_REPLACED.[A-Za-z0-9]*/This line is removed by the admin./'

其他回答

以上答案:

sed -i '/TEXT_TO_BE_REPLACED/c\This line is removed by the admin.' /tmp/foo

如果替换字符串/行不是变量,工作正常。

问题是在Redhat 5上,c后面的\转义了$。双\\也不起作用(至少在红帽5上)。

通过hit和trial,我发现如果替换字符串/行只有一行,那么c后面的\是多余的。所以我没有在c后面使用\,使用一个变量作为单一的替换行,它是joy。

代码看起来像这样:

sed -i "/TEXT_TO_BE_REPLACED/c $REPLACEMENT_TEXT_STRING" /tmp/foo

注意使用双引号而不是单引号。

bash-4.1$ new_db_host="DB_HOSTNAME=good replaced with 122.334.567.90"
bash-4.1$ 
bash-4.1$ sed -i "/DB_HOST/c $new_db_host" test4sed
vim test4sed
'
'
'
DB_HOSTNAME=good replaced with 122.334.567.90
'

它运行正常

到目前为止提供的所有答案都假设您了解要替换的文本,这是有意义的,因为这是OP所要求的。我提供的答案假设您对要替换的文本一无所知,并且文件中可能有与您不希望被替换的内容相同或类似的单独行。此外,我假设您知道要替换的行号。

下面的例子演示了如何通过特定的行号删除或更改文本:

# replace line 17 with some replacement text and make changes in file (-i switch)
# the "-i" switch indicates that we want to change the file. Leave it out if you'd
#   just like to see the potential changes output to the terminal window.
# "17s" indicates that we're searching line 17
# ".*" indicates that we want to change the text of the entire line
# "REPLACEMENT-TEXT" is the new text to put on that line
# "PATH-TO-FILE" tells us what file to operate on
sed -i '17s/.*/REPLACEMENT-TEXT/' PATH-TO-FILE

# replace specific text on line 3
sed -i '3s/TEXT-TO-REPLACE/REPLACEMENT-TEXT/'

我经常使用regex从文件中提取数据,我只是用它来替换文字引号\"与// nothing:-)

cat file.csv | egrep '^\"([0-9]{1,3}\.[0-9]{1,3}\.)' | sed  s/\"//g  | cut -d, -f1 > list.txt

在我的makefile中,我使用这个:

@sed -i '/.*Revision:.*/c\'"`svn info -R main.cpp | awk '/^Rev/'`"'' README.md

PS:不要忘记-i实际上改变了文件中的文本…因此,如果你定义为“Revision”的模式将改变,你也将改变模式来替换。

示例输出:

abc项目由John Doe撰写 修改:1190

因此,如果你设置模式“Revision: 1190”,这显然与你将它们定义为“Revision:”不同……