Adding XML element in XML file using sed command in shell script

前端 未结 3 517
滥情空心
滥情空心 2020-12-18 03:51

I am using sed command to insert an xml element into the existing xml file.

I have xml file as


    
        

        
3条回答
  •  暖寄归人
    2020-12-18 04:39

    You cannot have an unescaped newline in sed replacement text, that is $CONTENT in your example. sed uses the newline just like the shell does, to terminate a command.

    If you need a newline in the replacement text, you need to precede it with a backslash.

    There is another way to add text using the r option. For example:

    Lets say your main file is;

    $ cat file
    
        
            john
            123
        
        
            mike
            234
        
    
    

    You text you want to add is in another file (not variable):

    $ cat add.txt
        
            NewName
            NewID
        
    

    You can do (using gnu sed):

    $ sed '/<\/Students>/{ 
        r add.txt
        a \
        d 
    }' file
    
        
            john
            123
        
        
            mike
            234
        
        
            NewName
            NewID
        
    
    

    However, having given this option, it is still a very bad idea to parse xml with regular expression. It makes the solution very fragile and easy to break. Consider this as a learning exercise only.

提交回复
热议问题