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

前端 未结 23 887
别跟我提以往
别跟我提以往 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

    I finally got this to work in a Bash script used to insert a unique timestamp in each item in an RSS feed:

            sed "1,/====RSSpermalink====/s/====RSSpermalink====/${nowms}/" \
                production-feed2.xml.tmp2 > production-feed2.xml.tmp.$counter
    

    It changes the first occurrence only.

    ${nowms} is the time in milliseconds set by a Perl script, $counter is a counter used for loop control within the script, \ allows the command to be continued on the next line.

    The file is read in and stdout is redirected to a work file.

    The way I understand it, 1,/====RSSpermalink====/ tells sed when to stop by setting a range limitation, and then s/====RSSpermalink====/${nowms}/ is the familiar sed command to replace the first string with the second.

    In my case I put the command in double quotation marks becauase I am using it in a Bash script with variables.

提交回复
热议问题