CrudeCoder
CrudeCoder

Reputation: 401

Replace a row in a csv file

So i have a csv file:

Today</span><span class='invisible'>3:00 p.m. Nov. 29, 2013
Today</span><span class='invisible'>1:52 p.m. Nov. 29, 2013
Today</span><span class='invisible'>12:50 p.m. Nov. 29, 2013
Today</span><span class='invisible'>11:42 a.m. Nov. 29, 2013
Today</span><span class='invisible'>9:56 a.m. Nov. 29, 2013
Nov. 27, 2013
Nov. 27, 2013
Nov. 27, 2013
Nov. 27, 2013
Nov. 25, 2013

and I need to replace all the rows that start with Today and replace it with the date that is currently in the line. So far I've been running a for-loop:

rownumber=$(wc -l < DateStamp.csv)
for ((i=1; i<=$rownumber; i++))
do
    s1=$(awk -v "row=$i" -F'@' 'NR == row { print $1 }' DateStamp.csv)
    if [[ "$s1" =~ 'Today' ]]
        then
            year=$(date +'%Y')
            text=$(awk -v "row=$i" -F'@' 'NR == row { print $1 }' DateStamp.csv | grep -o -P "(?<=m\. ).*(?<=$year)")
                            __SOME COMMAND__
        else
            break
    fi
done

I want my output to be this:

Nov. 29, 2013
Nov. 29, 2013
Nov. 29, 2013
Nov. 29, 2013
Nov. 29, 2013
Nov. 27, 2013
Nov. 27, 2013
Nov. 27, 2013
Nov. 27, 2013
Nov. 25, 2013

Is there a line which I can replace with SOME COMMAND that will replace the row I am in with my variable text? Maybe a sed or awk command?

Upvotes: 2

Views: 553

Answers (2)

Jotne
Jotne

Reputation: 41460

You can do this easy with awk

awk '/^Today/ {$0=$4 FS $5 FS $6}1' DateStamp.csv
Nov. 29, 2013
Nov. 29, 2013
Nov. 29, 2013
Nov. 29, 2013
Nov. 29, 2013
Nov. 27, 2013
Nov. 27, 2013
Nov. 27, 2013
Nov. 27, 2013
Nov. 25, 2013

If line starts with Today, set line equal to field 4,5 and 6. Then print everything out.

Upvotes: 2

iruvar
iruvar

Reputation: 23394

Assuming that the presence of a.m. or p.m. in front of the date is guaranteed, do you really need to parse and extract the date from the Today lines? The following may suffice

sed 's/.*[ap]\.m\.\s\+\(.*\)$/\1/' DateStamp.csv

This uses a capture group \(.*\) to collect the portion after a.m or p.m. and replaces the entire input line with the contents of this capture group. just passes through the original line otherwise

Upvotes: 2

Related Questions