简体   繁体   中英

How to replace a string on sed

Hi i made a script which is take a data from my db and store it in to a .csv file

the contents of .csv file:

1-Mar-12,183991,1017  --- --- more columns are there
2-Mar-12,,,,,,,,,,,,
3-Mar-12,,,,,,,,,,,,
4-Mar-12,,,,,,,,,,,,
5-Mar-12,,,,,,,,,,,,
6-Mar-12,,,,,,,,,,,,

when i trying to replace a string depends upon the date it will add all corresponding dates.

for example

i want to replace a string on 2-Mar-12

command is

sed "s/$finddate/$finalstring/" dailyrep.csv > DailyReport_$datenow.csv


sed "s/2-Mar-12/$mydata/" origfile > fileto store

Output is

2-Mar-12,177950,8159,95.62%,6785711
3-Mar-12,,,,,,,,,
4-Mar-12,,,,,,,,,
5-Mar-12,,,,,,,,,
6-Mar-12,,,,,,,,,

11-Mar-12,,,,,,,,,,,,,,,,,,,,
12-Mar-12,177950,8159,95.62%,


21-Mar-12,,,,,,,,,,,,,,,,,,,
22-Mar-12,177950,8159,95.62%

I want to replace only that particular date not all occurrence of that.

You can use this sed command:

$ sed "/^$finddate/s/$mydata/$finalstring/" dailyrep.csv

It only replace $mydata to $finalstring on lines which contain $finddate .

^ in regular expressions means "beginning of the line". So what you need is to change "s/2-Mar-12/$mydata/" to "s/^2-Mar-12/$mydata/" . It works not only in sed, of course.

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