Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing first column csv with variable

Tags:

bash

csv

sed

awk

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.

like image 717
CrudeCoder Avatar asked Feb 25 '14 03:02

CrudeCoder


People also ask

How do I find and replace in a CSV file?

When working with a CSV file it is often necessary to find data contained within and sometimes replace it. Find & Replace is used for just this. You can access it from the Edit > Find & Replace menu or by pressing Ctrl-F on the keyboard.

How do I replace a string in a CSV file in Python?

The join() method takes all lines of a CSV file in an iterable and joins them into one string. Then, we can use replace() method on the entire string and can perform single/multiple replacements. In the entire string, the given text is searched and replaced with the specified text.


1 Answers

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.
like image 65
jaypal singh Avatar answered Sep 19 '22 05:09

jaypal singh