简体   繁体   中英

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. I am not sure how to do this. I have read a few questions on stack overflow about using "sed" to replace the line. 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:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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