我想使用sed(在MacO上)用另一个文件的内容替换文件中的某些行。
假设文件如下,我想替换包含的所有行<iframe src=...0></iframe>
。
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Paupertas si malum est, mendicus beatus esse nemo
<iframe src="https://test.com/bar/11d75d1c627c017299e4fe35e" frameborder=0></iframe>
oportunitatis esse beate vivere. Quasi vero, inquit, perpetua oratio rhetorum solum, non etiam philosophorum
<iframe src="https://test.com/bar/9e4e1b69131bf5d718452aca6" frameborder=0></iframe>
vivere. Quasi vero, inquit, perpetua oratio rhetorum solum, non etiam philosophorum
在命令行上,以下命令运行良好:
$ sed -i '' -e "/$line/r $replacementFile" -e "//d" $originalFile
哪里
$line
是改变的线line="\<iframe src=\"https:\/\/test\.com\/bar\/11d75d1c627c017299e4fe35e\" frameborder=0\>\<\/iframe\>"
$replacementFile
指向其内容必须替换$line
s的文件,其内容如下:LOREM IPSUM DOLOR
AMET, CONSECTETUR
ADIPISCING ELIT.
$originalFile
是$line
必须更改的文件的路径我要修改几个文件,每个文件都包含几行要更改的内容。因此,我编写了一个脚本,其中所有类型的行都<iframe src=...0></iframe>
使用正则表达式找到,然后应用在命令行上有效的命令。
以下是我编写的原始脚本:
function replaceTextWithFile() {
# File to modify (in production the name is passed as an argument)
local originalFile="./file.txt"
# Regex to find the line to change
local regex="<iframe src=\"(https:\/\/test.*)\" frameborder"
# Regex on "normal" line does not work neither
#local patternToReplace="^oportu.*"
# The file whose content must replace the line
local replacementFile="./new_content"
exec 4<"$originalFile"
while read line <&4 ; do
if [[ $line =~ $regex ]];then
echo "PATTERN FOUND"
sed -i '' -e '/$line/r $replacementFile' -e '//d' $originalFile
fi
# Following command changes the 9th line successfully
sed -i '' -e "12s/.*/TEST TEST/" $originalFile
done
exec 4<&-
}
replaceTextWithFile
但是文件没有更改。
我认为,什么都没有发生,因为我想改变线有一些特殊字符(<
,/
,...),但剧本不还的“正常”的线上工作。
我还认为问题是因为该文件以描述符文件的读取模式打开,但是我可以使用sed更改文件的内容,例如,使用以下命令:
sed -i '' -e "9s/.*/TEST TEST/" $originalFile
我尝试了好几种语法没有成功,你可以找到脚本和不同的语法,我试图在这里。
有人知道我在做什么错吗?
关于Stackoverflow,有几个问题可以解决此类问题,但是它们都没有帮助。
如果我的初衷是用sed替换行,则可以使用其他解决方案。
您的脚本有一些错误:
sed
适用于正则表达式,不适用于确切的字符。因此/$line/
将被解析为正则表达式。'/$line/'
匹配字面上5个字符$line
。要扩展变量,请使用双引号。bash中单引号和双引号之间的stackoverflow差异。sed
。sed
已经在每一行上执行了...function func() {
bash支持bash作为扩展来支持奇怪的语法,因此不应使用它。只是func() {
定义一个函数。bash-hackers Wiki已弃用且过时的语法。Following command changes the 9th line successfully
后面是更改第12行的行。because the lines that I want to change have some particular characters
在<
和>
在正则表达式没有特殊含义,但是\<
\>
是一个GNU sed的扩展。学习带有正则表达式填字游戏的正则表达式。IFS= read -r line
。bashfaq如何逐行读取文件。只是:
replaceTextWithFile() {
local originalFile="./file.txt"
local regex="<iframe src=\"https:\/\/.*\" frameborder"
local replacementFile="./new_content"
# note -i '' on macos I think
sed -i -e "/$regex/r $replacementFile" -e '//d' "$originalFile"
}
请注意,正则表达式可以更简单地用单引号引起来,因此"
不需要转义:
local regex='<iframe src="https:\/\/.*" frameborder'
或者甚至可以使用其他正则表达式定界符sed
来使其变得简单:
local regex='<iframe src="https://.*" frameborder'
sed "\~$regex~r $replacementFile"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句