0

I am trying to add new row in starting of csv file. I have csv file as below

cat data.csv

2012710000,07-FEB-21
2013330011,08-DEC-20

I want output add BatchID in start of line like below

BatchID,<<some user input>
2012710000,07-FEB-21
2013330011,08-DEC-20

Please guide me.

CrazyCoder
  • 622
  • 5
  • 10
  • 27
  • 2
    Like that `printf 'BatchID,<\n' && cat data.csv`? – Arkadiusz Drabczyk Feb 22 '21 at 11:35
  • Does this answer your question? [How to insert a text at the beginning of a file?](https://stackoverflow.com/questions/9533679/how-to-insert-a-text-at-the-beginning-of-a-file) – costaparas Feb 22 '21 at 11:56
  • In this case, the fact that you are dealing with a CSV file is irrelevant, the methods outlined in the duplicate I linked will suffice for your needs. (The question essentially reduces to adding a line to the start of a file). – costaparas Feb 22 '21 at 11:57
  • @costaparas Close, but that one's about prepending to the first line, not inserting a line before the current first one. – Shawn Feb 22 '21 at 11:58
  • @shawn OK thx, I just searched and that's the one that popped up, I thought it was the right one, but I'm sure there must be a dupe of this somewhere. – costaparas Feb 22 '21 at 11:59
  • @costaparas Admittedly, it does seem to have a lot of answers from people who missed that part of the question. – Shawn Feb 22 '21 at 12:00
  • @shawn haha yeah you're right, so then I guess that link will suffice in this case. I had a quick look and couldn't find a more relevant dupe, so maybe someone else can suggest one. – costaparas Feb 22 '21 at 12:02
  • 1
    Does this answer your question? [Shell one liner to prepend to a file](https://stackoverflow.com/questions/54365/shell-one-liner-to-prepend-to-a-file) – Shawn Feb 22 '21 at 12:03

2 Answers2

0

Using awk:

awk 'BEGIN { print "BatchID,<<some user input>" } { print } data.csv > data.tmp && mv -f data.tmp data.csv

Print the text in the BEGIN block before processing the rest of the file and printing the lines. Output the results to data.tmp and then move data.tmp to data.csv.

Using sed:

sed -i '1aBATCHID,<<some user input>' data.csv

Process the 1st line and append the data as required.

Raman Sailopal
  • 10,979
  • 2
  • 6
  • 15
0

I am able to do that using below command

echo "BATCHID"$id  | cat - data.csv>/tmp/out && mv /tmp/out data.csv
CrazyCoder
  • 622
  • 5
  • 10
  • 27