Adding a new column to a CSV file

放肆的年华 提交于 2020-01-07 06:40:21

问题


I have a CSV file that looks like this:

"12345","TestTest","1.2","TestTest
"

I want to add a date such as YYYY-MM-DD HH:MM:SS to either the beginning or the end of the CSV file. As you can see in the example above, the double quote (") encases the values on the columns and the comma (,) delineates each column. The problem is the double quote at the end of the line is always on a new line. This means that when I've tried to use sed to search/replace based on a single double quote, my replacement ends up not only at the start of the line, but also at the end of the line.

My next theory is if its possible to use some tool (sed, awk, whatever) to add in the date only when the beginning of the CSV line is a double quote and a number ie: "12345", so the new line looks like:

"YYYY-MM-DD HH:MM:SS","12345","TestTest","1.2","TestTest
"

NOTE: This command you suggest should apply this change to every line in the CSV file. This also needs to be run via linux command line.

Thanks,


回答1:


With sed:

sed 'N;s/^/"YYYY-MM-DD HH:MM:SS",/' file

If you want to make sure there is a single " on next line:

sed 'N;/\n"$/s/^/"YYYY-MM-DD HH:MM:SS",/' file

Edit:

To insert the string after 5th field:

sed 'N;s/","/","YYYY-MM-DD HH:MM:SS","/5' file



回答2:


awk to the rescue!

$ awk -F, 'NF>1{$0 = "\"YYYY-MM-DD\"" FS $0}1' file

NF>1 test check whether there are more than one field on the line, if so prepend it with the new field, the 1 at the end is shorthand for {print}.




回答3:


I suggest to use a csv parser to avoid problem with fields that may contain the delimiter or new lines. You can use the Text::CSV module in a perl command line. An example to insert a string in the 4th column:

perl -MText::CSV -E'$csv = Text::CSV->new({binary=>1}); 
while ($row = $csv->getline(STDIN)){
    splice @$row, 3, 0, "YYYY-MM-DD";
    say "\"", join("\",\"",@$row), "\""
}' file.csv


来源:https://stackoverflow.com/questions/42052462/adding-a-new-column-to-a-csv-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!