Badri M
Badri M

Reputation: 25

How to add a value of the variable at the beginning of a csv file

I have a CSV file (sample1.csv) in which I need to add the value of x as the first column of the entire CSV. My code looks like this,

code:

x=24 feb 20 12:29:30
awk -v d="$x" -F"," 'BEGIN { OFS = "," } {$1=d; print}' sample1.csv > sample2.csv

The above one replaces the first field of the CSV with x value instead of appending x value at the beginning.

sample1.csv

TV,Sony,40,smart
TV,LG,32,smart

sample2.csv [expected output]

24 feb 20 12:29:30,TV,Sony,40,smart
24 feb 20 12:29:30,TV,LG,32,smart

Thanks

Upvotes: 0

Views: 772

Answers (4)

Mark
Mark

Reputation: 4455

You are soooo close. Try this:

x="24 feb 20 12:29:30"
awk -v d="$x"  'BEGIN { OFS = "," } {print d,$0 }' sample1.csv > sample2.csv

Upvotes: 1

aborruso
aborruso

Reputation: 5688

Using Miller (https://github.com/johnkerl/miller) is

mlr --csv -N put '$value="24 feb 20 12:29:30"' then reorder -f value input.csv >output.csv

Upvotes: 0

anubhava
anubhava

Reputation: 785156

You may use this awk to prepend variable before $1;

awk -v d="$x" 'BEGIN{FS=OFS=","} {$1=d OFS $1} 1' file.csv

Or use this awk with sub function call that replaces line start with variable value and your field separator (comma):

awk -v d="$x" -F, '{sub(/^/, d FS)} 1' file.csv

24 feb 20 12:29:30,TV,Sony,40,smart
24 feb 20 12:29:30,TV,LG,32,smart

Upvotes: 1

karakfa
karakfa

Reputation: 67497

easier with sed

$ sed 's/^/24 feb 20 12:29:30,/' file

Upvotes: 1

Related Questions