1

I want to rename the header of a csv file using bash script. Original csv file header looks like below:

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
3
  • Are the columns separated by spaces or tabs? Commented Nov 29, 2017 at 4:11
  • My bad. Columns separated by ,. Commented Nov 29, 2017 at 4:15
  • 1
    echo new header, then use tail -n +2 to output original csv file from the second line. Commented Nov 29, 2017 at 4:28

2 Answers 2

1

You can use sed replace the header or the first line:

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. In case you do, use a different separator in the sed expression.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks. Will this work when my columns are separated by ,? I am working first time on bash script. My questions might sound stupid.
, shouldn't be an issue. However, ; can be.
@codeforester, I am getting error ./BASH.SH: line 2: $'\r': command not found while running this code new_header="Cell,id,too,Issue,Valid,DPT,RH,TMP,U,V" sed -i '' "1s/.*/$new_header/" temp.csv. Any comments?
Windows 8, I am using.
Thank you so much @codeforester. It's finally working.
|
0

You need to replace the first line with a different line. sed can do it for you:

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)
  • -e following is a sed command
  • 1 execute the commands in the {} when you see the first line of input
  • r inserts the text from the following "file"
  • <( 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)
  • d deletes the line

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

2 Comments

Thanks @chutz!. But When I am running this command I am getting the following error sed: cannot rename ./sedTKtPM3: Device or resource busy. How to resolve this?
@Kaushik, could be permissions.

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.