7

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.

5 Answers 5

12

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Very well explained @Jaypal +1
That's the first time I've received an explanation of the 1 after the curly brackets or parentheses (round brackets.) That helps me understand some other commands.
2
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.

1 Comment

sed "s|[^,]*|$( date +'%d/%m/%y' )|" YourFile do all at once
1
perl -pe 's/.*?,/2\/24\/14/' your_file

tested here

Comments

1

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"

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.