我有一个文本文件,其中有一行
sometext sometext sometext TEXT_TO_BE_REPLACED sometext sometext sometext
我需要将上面的整行替换为
This line is removed by the admin.
搜索关键字是text_to_be_replace
我需要为此写一个shell脚本。如何使用sed实现这一点?
我有一个文本文件,其中有一行
sometext sometext sometext TEXT_TO_BE_REPLACED sometext sometext sometext
我需要将上面的整行替换为
This line is removed by the admin.
搜索关键字是text_to_be_replace
我需要为此写一个shell脚本。如何使用sed实现这一点?
当前回答
下面的命令对我有用。哪个是处理变量的
sed -i "/\<$E\>/c $D" "$B"
其他回答
这和上面那个很相似。
sed 's/[A-Za-z0-9]*TEXT_TO_BE_REPLACED.[A-Za-z0-9]*/This line is removed by the admin./'
cat find_replace | while read pattern replacement ; do
sed -i "/${pattern}/c ${replacement}" file
done
Find_replace文件包含2列,c1为匹配模式,c2为替换,sed循环替换包含变量1的模式之一的每一行
您可以使用change命令替换整行,并使用-i标志进行适当的更改。例如,使用GNU sed:
sed -i '/TEXT_TO_BE_REPLACED/c\This line is removed by the admin.' /tmp/foo
要做到这一点,不依赖任何GNUisms,如-i不带参数或c不带换行符:
sed '/TEXT_TO_BE_REPLACED/c\
This line is removed by the admin.
' infile > tmpfile && mv tmpfile infile
在这种(POSIX兼容的)命令形式中
c\
text
文本可以由一行或多行组成,应该成为替换的一部分的换行符必须转义:
c\
line1\
line2
s/x/y/
其中s/x/y/是一个新的sed命令后,模式空间已替换为两行
line1
line2
到目前为止提供的所有答案都假设您了解要替换的文本,这是有意义的,因为这是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/'