0

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.

0

2 Answers 2

3

You can use this sed command:

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

Try: sed "/^$finddate/s/$mydata/$finalstring/"
You can add ^ to the pattern to match the beginning of line.
Adding ^ the beginning of a regular expression means that the pattern will only match if it's at the beginning of the string. As you saw, sed matched any occurrence of '2-Mar-12', including '12-Mar-12', '22-Mar-12', etc. Adding ^ to the regex means it will only match lines that start with '2-Mar-12'.
1

^ 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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.