linux - 在linux中插入一行包含sed命令的文件

标签 linux sed

我正在尝试在一个文件中插入行,该文件将有一个 sed 命令在另一个文件中插入行 就像下面的例子: 想要将此行 sed -i '1s/^/insideFile\n/' secondaryFile.sh 添加到 firstfile.txt 的第 65

我尝试过:

sed -i '65s/^/\'sed -i \'1s/^/insideFile\n/\' secondFile.sh\'\n/' firstfile.sh

但无法转义'

也尝试过

sed -i "65s/^/'sed -i "1s/^/topLine\n/" $FILE_HOME_LOCAL_FILE'\n/" secondFile.sh

但是得到了 sed:-e 表达式 #1,字符 18:`s 的未知选项

最佳答案

您可以使用这个sed:

sed -i.bak "65s~^~sed -i '1s/^/insideFile\\\\n/' secondFile.sh\\n~" firstfile.sh

注意:

  • 使用备用分隔符~以避免转义/
  • sed 命令中使用双引号以避免转义单引号
  • 使用\\\\插入单个\
  • 在双引号内使用 \\n 插入换行符

或者用i(插入)代替s(替代):

sed -i.bak "65i\\
sed -i '1s/^/insideFile\\\\n/' secondFile.sh\\
" firstfile.sh

最干净的解决方案是创建一个像这样的 sed 脚本,从而避免所有引用和额外的转义:

cat ins.sed
65i\
sed -i '1s/^/insideFile\\n/' secondFile.sh

然后将其用作:

sed -i.bak -f ins.sed firstfile.sh

关于linux - 在linux中插入一行包含sed命令的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74106075/

相关文章:

python - 如何使用子进程从函数返回变量?

linux - 奇数如何解决分布式系统中的脑裂?

linux - 有什么办法可以在模式匹配后在 sed 中增加一些数字

awk - 用键分隔行并存储在不同的文件中

java - 正则表达式:对匹配组执行操作

linux - 当我执行 "rm -rf data"时,删除顺序是什么?

linux - shell "${i%,v}"在 run-parts.sh 中是什么意思?

bash - 删除文件中不包含白名单字符的行

linux - 如何在 bash 中分解极长的字符串文字?

awk - 如何在特定模式后的换行符之间使用 sed 或 awk 提取?