You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shell脚本文件的指定中间位置追加命令

解决方案

步骤1:提取域名并生成格式化内容

假设存储路径的文件名为paths.txt,先从中提取域名部分并生成带有序数标识的内容:

awk -F'/' '
BEGIN {
    # 定义对应序数词,可按需扩展
    ords[4] = "fourth"
    ords[5] = "fifth"
    ords[6] = "sixth"
}
{
    print ords[NR+3] " domain: " $NF
}
' paths.txt > insert_content.txt

执行后insert_content.txt的内容为:

fourth domain: hello.co.uk.pem
fifth domain: stack.co.uk.pem
sixth domain: overflow.co.uk.pem

步骤2:插入到目标脚本指定位置

假设目标脚本文件名为script.sh,将上述内容插入到#before this command行的上方:

  • Linux(GNU sed):
sed -i '/^#before this command/r insert_content.txt' script.sh
  • macOS(BSD sed):
sed -i '' '/^#before this command/r insert_content.txt' script.sh

执行后脚本末尾会变成预期效果:

fourth domain: hello.co.uk.pem
fifth domain: stack.co.uk.pem
sixth domain: overflow.co.uk.pem

#before this command (this will be an actual command, and must be at the end of the file)

一步到位(无需临时文件)

如果不想生成中间文件,可直接通过管道完成:

awk -F'/' '
BEGIN {
    ords[4] = "fourth"
    ords[5] = "fifth"
    ords[6] = "sixth"
}
{
    print ords[NR+3] " domain: " $NF
}
' paths.txt | sed -i '/^#before this command/e cat /dev/stdin' script.sh

内容的提问来源于stack exchange,提问作者NewCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 23:52:45