Reputation: 393
I'm trying to write a BASH script that will append :00:00 to the end of all values in the 2nd field of a CSV file.
I've tried reading through 'awk' man pages but I'm not understanding how I can complete this. Any help is appreciated!
2012-02-29,00,Manhatten,New York,244
2012-02-29,01,Manhatten,New York,246
2012-02-29,02,Manhatten,New York,554
2012-02-29,03,Manhatten,New York,854
2012-02-29,04,Manhatten,New York,488
2012-02-29,00:00:00,Manhatten,New York,244
2012-02-29,01:00:00,Manhatten,New York,246
2012-02-29,02:00:00,Manhatten,New York,554
2012-02-29,03:00:00,Manhatten,New York,854
2012-02-29,04:00:00,Manhatten,New York,488
Upvotes: 0
Views: 3938
Reputation: 58578
This might work for you:
sed 's/,/:00:00,/2' file
2012-02-29,00:00:00,Manhatten,New York,244
2012-02-29,01:00:00,Manhatten,New York,246
2012-02-29,02:00:00,Manhatten,New York,554
2012-02-29,03:00:00,Manhatten,New York,854
2012-02-29,04:00:00,Manhatten,New York,488
or this:
awk '{sub(/,../,"&:00:00")}1' file
2012-02-29,00:00:00,Manhatten,New York,244
2012-02-29,01:00:00,Manhatten,New York,246
2012-02-29,02:00:00,Manhatten,New York,554
2012-02-29,03:00:00,Manhatten,New York,854
2012-02-29,04:00:00,Manhatten,New York,488
Upvotes: 0
Reputation: 1867
Below is a command to filter the conversion:
awk 'BEGIN { FS=","; OFS="," } (NF>=2) { $2=$2 ":00:00"; } (1)'
If you have a file source.txt
which store source data and a file result.txt
to be stored the output, following command will do:
awk 'BEGIN { FS=","; OFS="," } (NF>=2) { $2=$2 ":00:00"; } (1)' source.txt >result.txt
If you have multiple input files, you can add them in arguments. See manpage of awk for more details.
Upvotes: 1
Reputation: 17546
You can use sed
as well (which would be my first choice) but using awk
is fine too..
What you need is to extract value in each column, and just print them back, but while printing the second column, append your :00:00
.
see this example, give it a try and get back if you have some specific questions:
$ cat a.txt
2012-02-29,00,Manhatten,New York,244
2012-02-29,01,Manhatten,New York,246
2012-02-29,02,Manhatten,New York,554
2012-02-29,03,Manhatten,New York,854
2012-02-29,04,Manhatten,New York,488
$ awk -F , '{print $1 "-" $2 "-" $3 "-" $4 "-" $5}' a.txt
2012-02-29 - 00 - Manhatten - New York - 244
2012-02-29 - 01 - Manhatten - New York - 246
2012-02-29 - 02 - Manhatten - New York - 554
2012-02-29 - 03 - Manhatten - New York - 854
2012-02-29 - 04 - Manhatten - New York - 488
$
Upvotes: 0
Reputation: 21597
One liner with perl
perl -F, -nae '$F[1].=":00:00";print join(",", @F);'
Upvotes: 0