3

I split a number of csv files into two halves each. But every of those files had a header, so now the second halves of the files are missing headers.

How do I insert the top line of file A into the top of file B?

Denys
  • 4,287
  • 8
  • 50
  • 80

2 Answers2

4

using command substitution to extract the first line of file1 and then using sed in place replacement for first line in file2.

 sed -i "1s/^/$(head -n1 file1)\n/" file2
P....
  • 17,421
  • 2
  • 32
  • 52
  • Thx. Can you please what's happening inside " "? – zniv Jul 18 '19 at 18:33
  • `1s1 in the `sed` command means, search and replace only on first line. `^` means start of the line. and `head -n1 file1` will get the first line of file1. So `/^/$(head -n1 file1)/` means replace first line of file2 with first line of file1. – P.... Jul 18 '19 at 20:15
1

You have to rewrite the second file. Assuming that you have the files first.csv and second.csv you can do it like that:

head -n1 first.csv > second-new.csv
cat second.csv >> second-new.csv

You can now inspect second-new.csv to see if everything is ok and then replace the old version with:

mv -i second-new.csv second.csv
redneb
  • 21,794
  • 6
  • 42
  • 54