向CSV文件添加新列 [英] Adding a new column to a CSV file

查看:218
本文介绍了向CSV文件添加新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的CSV文件:

I have a CSV file that looks like this:

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

我想将YYYY-MM-DD HH:MM:SS之类的日期添加到CSV文件的开头或结尾.如您在上面的示例中看到的那样,双引号()将列中的值括起来,而逗号(,)则在每一列中画出轮廓.问题在于,行尾的双引号始终位于新行上.这意味着当我尝试使用sed来基于单双引号进行搜索/替换时,我的替换不仅会在行的开头,而且会在行的结尾处结束.

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.

我的下一个理论是,是否有可能仅在CSV行的开头为双引号和数字(例如:"12345")时使用某些工具(sed,awk等)在日期中添加内容线看起来像:

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
"

注意:建议您将此命令应用于CSV文件中的每一行.这也需要通过linux命令行运行.

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.

谢谢

推荐答案

使用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

要在第5个字段后插入字符串:

To insert the string after 5th field:

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

这篇关于向CSV文件添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆