简体   繁体   中英

Replace only the First occurrence of a string in a file using sed

I have the following sed command :

sed 's'~"-log -asofdate $newAsOfDate "'~'"-log1"'~1'  /export/home/ownclp/temp/runjava.sh.bk > $runjavaPath

but instead of replacing just the first occurrence it is replacing all occurrence. Note : ~ is my delimiter.

How do I solve this?

Assuming you mean you want to replace only the first instance of the pattern on the first line where it appears you want something like this:

sed "0,/-log -asofdate $newAsOfDate /s~-log -asofdate $newAsOfDate ~-log1~"  /export/home/ownclp/temp/runjava.sh.bk > "$runjavaPath"

As $newAsOfDate appears to have a / in it you would need to use an alternate address regex marker like this instead:

sed "0,\~-log -asofdate $newAsOfDate ~s~-log -asofdate $newAsOfDate ~-log1~"  /export/home/ownclp/temp/runjava.sh.bk > "$runjavaPath"

This might work for you (GNU sed):

sed '\~-log -asofdate '"$newAsOfDate"' ~{s//-log1/;:a;n;ba}' oldFile >newFile

This substitutes the required string for the first match and then reads and prints the remainder of the file.

This alternative may work for you:

sed -e '\~-log -asofdate '"$newAsOfDate"' ~!b' -e 's//-log1/' -e ':a' -e 'n' -e 'ba' oldFile >newFile

The first command is a match on any address that contains the required string. The alternate delimiter ~ is used incase the shell variable "$newAsOfDate" contains the default / delimiter. If a match is not made (hence !b ) the line is printed as normal, the command b means break from the sequence of commands following and as there is no place holder following the b print the current command begins again at the first command. The second -e statement means following a match, substitute the matched part of the previous address and replace it with -log1 . The next three statements set up the mechanism of a loop. The first is a namespace or loop place holder :a , the second command n means print the current line and then replace the pattern space with the next line, and lastly the ba command means return to the loop place holder :a . The n command also quits any outstanding commands once the last line has been printed.

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