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/

相关文章:

c - 线程与进程 : icmp packet creation fails in thread

Linux 脚本在两台服务器的 ksh 上表现不同

regex - 如何在 vim 中使用正则表达式来切换文件中所有字符的大小写

linux - 如何在 rm 中为特定目录使用 ls 命令输出

bash -/etc/bashrc 中的函数未通过变量传递引号

bash - sed 不写入文件

awk - 使用 sed/awk 从重复行中删除模式

linux - 系统调用如何知道文件描述符属于哪个进程?

php - 通过 php shell_exec 执行 bash 脚本的权限错误

linux - 比较连续行的前 5 个字符 - shell 脚本