CrudeCoder
CrudeCoder

Reputation: 401

Replacing first column csv with variable

I can't believe I couldn't find my question anywhere else in the bash/linux community. I simply want to replace the first column of my csv file with a variable...

0,8,9,10
0,8,9,10
0,8,9,10
0,8,9,10
0,8,9,10
0,8,9,10


2/24/14,8,9,10
2/24/14,8,9,10
2/24/14,8,9,10
2/24/14,8,9,10
2/24/14,8,9,10
2/24/14,8,9,10

I simply just want to replace the first column with $date, but all the awk commands don't allow a variable as a the replacement.

Upvotes: 7

Views: 6068

Answers (5)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26141

Every time you deal with complex data format you should use proper parser and CSV is complex data format (and without any proper definition and full of quirks. No RFC 4180 is not the definition. It is rather joke. There is a lot of data violating RFC 4180 and almost every decent CSV parser out there is ignoring this RFC because it would not work.)

perl -mText::CSV_XS -e'$d=shift@ARGV;$csv=Text::CSV_XS->new({ binary => 1, eol => $/ });while(my$row=$csv->getline(*ARGV)){$$row[0]=$d;$csv->print(*STDOUT,$row)}' "$date"

Upvotes: 1

Vijay
Vijay

Reputation: 67319

perl -pe 's/.*?,/2\/24\/14/' your_file

tested here

Upvotes: 1

Jotne
Jotne

Reputation: 41460

Changing to current date using awk

echo "0,8,9,10" | awk '{sub(/[^,]+/,d)}8' d="$(date +'%d/%m/%y')"
25/02/14,8,9,10

[^,]+ everything that is not a , will be replaced with d date

Upvotes: 0

unxnut
unxnut

Reputation: 8839

sed 's#^[^,]*#2/24/14#' filename

should do it. If you want to work with the current date, you should do:

DATE=$(date +'%d/%m/%y')
sed "s#^[^,]*#$DATE#" filename

This is looking for the first item before the comma and replace it with the date. The use of # as delimiter allows you to type in the date without having to escape the / character.

Upvotes: 2

jaypal singh
jaypal singh

Reputation: 77185

This should work:

awk -v dt="$date" 'BEGIN{FS=OFS=","}{$1=dt}1' inputFile

Explaination:

  • Use -v option to set an awk variable and assign it your shell variable.
  • Set the Input Field Separator and Output Field Separator to , (since it is a csv)
  • Set the value of $1 to your awk variable.
  • 1 is to print the line with modified $1.

Upvotes: 12

Related Questions