简体   繁体   English

使用bash脚本重命名csv标头

[英]Rename csv header using bash script

I want to rename the header of a csv file using bash script. 我想使用bash脚本重命名csv文件的标题。 Original csv file header looks like below: 原始的csv文件标头如下所示:

temp.csv
    ,id,too,Issue,Valid,DPT,RH,TMP,U,V
    1,1,22383,2015-01-15 00:00:00 GMT,2015-01-15 00:00:00 GMT,269.8000183,80.90000153,272.6300049,3.039999962,-0.560000002
    1

            id  to  Issue   Valid   DPT RH  TMP U   V
      1     2    3  4        5      6   7    8  9   10

I 

want to rename column header as below: 要重命名列标题,如下所示:

 Cell   id  too Issue   Valid   DPT RH  TMP U   V
    1   2    3  4        5      6   7   8  9   10

You can use sed replace the header or the first line: 您可以使用sed替换标题或第一行:

new_header=" Cell   id  too Issue   Valid   DPT RH  TMP U   V"
sed -i '' "1s/.*/$new_header/" file

This assumes that you don't have the sed expression separator / in your new header. 假设您的新标头中没有sed表达式分隔符/ In case you do, use a different separator in the sed expression. 如果需要,请在sed表达式中使用其他分隔符。

You need to replace the first line with a different line. 您需要用不同的行替换第一行。 sed can do it for you: sed可以为您做到:

sed -i -e "1 { r"<(echo ' Cell   id  too Issue   Valid   DPT RH  TMP U   V')"
d
}" file

To expand on the command 扩展命令

  • -i edits the file in place (you can skip this) -i在适当位置编辑文件(您可以跳过此操作)
  • -e following is a sed command -e以下是sed命令
  • 1 execute the commands in the {} when you see the first line of input 1在看到输入的第一行时执行{}的命令
  • r inserts the text from the following "file" r从以下“文件”插入文本
  • <( echo ' ... ') produces the new header on standard output, and assigns it to a file that is then readable by the sed command ( r will insert that text) <( echo ' ... ')在标准输出上产生新的标头,并将其分配给sed命令可读的文件( r将插入该文本)
  • d deletes the line d删除行

So, insert a new line of text and delete the old one. 因此,插入新的文本行并删除旧的文本行。

If you do not need to edit the file in place, easier to do: 如果您不需要就地编辑文件,则更容易做到:

(
  echo ' Cell   id  too Issue   Valid   DPT RH  TMP U   V'
  tail -n +2 file
) > file.new

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM