How to use sed to replace only the first occurrence in a file?

前端 未结 23 856
别跟我提以往
别跟我提以往 2020-11-22 04:27

I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash s

23条回答
  •  [愿得一人]
    2020-11-22 04:45

    The following command removes the first occurrence of a string, within a file. It removes the empty line too. It is presented on an xml file, but it would work with any file.

    Useful if you work with xml files and you want to remove a tag. In this example it removes the first occurrence of the "isTag" tag.

    Command:

    sed -e 0,/'false<\/isTag>'/{s/'false<\/isTag>'//}  -e 's/ *$//' -e  '/^$/d'  source.txt > output.txt
    

    Source file (source.txt)

    
        
            true
            false
            
                esa_jee6
                false
            
            
                false
            
        
    
    

    Result file (output.txt)

    
        
            true
            
                esa_jee6
                false
            
            
                false
            
        
    
    

    ps: it didn't work for me on Solaris SunOS 5.10 (quite old), but it works on Linux 2.6, sed version 4.1.5

提交回复
热议问题