简体   繁体   English

如何对文件中已经存在的行的附加内容执行bash脚本

[英]How to bash script an addition to a line that already exists in a file

I am writing a script to automatically build a project. 我正在编写一个脚本来自动构建项目。 This will include adding items to the pom files and specific lines. 这将包括将项目添加到pom文件和特定行。 I am not sure how to do this. 我不确定该怎么做。 I have read a few questions on stack overflow about using "sed" to replace the line. 我已经阅读了有关使用“ sed”替换行的堆栈溢出问题。 But I am not sure that will work my case because I still need the original text which can change if someone manually changed it. 但是我不确定这是否可以解决我的问题,因为我仍然需要可以手动更改的原始文本。 My script needs to either add to the file or take what is there at the time and just add to the list. 我的脚本需要添加到文件中或使用当时的文件,然后添加到列表中。

Scenario 1: 方案1:

module_list=("one" "two" "three")

I have a file that has this line. 我有一个包含此行的文件。 I want to be able to add to this list every time I run my script to create a new module such that the final output is. 我希望每次运行脚本来创建新模块时都可以将其添加到此列表中,以使最终输出为。

module_list=("one" "two" "three"  "four")

Where "four" would be a parameter that is passed in when I run the script as $1. 其中“四个”是当我以$ 1运行脚本时传递的参数。

My third and final example would be to add code after a specific line. 我的第三个也是最后一个示例是在特定行之后添加代码。 For example when I add a module I would have to add a function in a file after the existing function. 例如,当我添加模块时,我必须在文件中的现有功能之后添加一个功能。

Before: 之前:

function OldModule()
{
    one 
}

I would want to add it after function such that 我想在功能之后添加它

 function OldModule()
    {
        one 
    }

     function Old$1()
        {
            two
        }

For the first scenario: 对于第一种情况:

sed -i '/module_list=/ s/)/ '"$1"')/' filename

If the value of $1 contains a slash, this will break. 如果$1的值包含斜线,则它将中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM