Title: add string to the beginning of a text file without new line
Tags: r;bash;cat
Question: So I am trying to import some massive tab separated txt file (200 MB) into R for statistical analysis. Unfortunately, the file format is inconsistent with the number of columns/rows. The first row contains the header names for all but the first two columns.
example:
header3 header4 header5
column1 column2 column3 column4 column5
I can repair the file after reading it into R, but the more elegant way would be to insert header1 header2 into the file.
I tried:
cat file_with_missing_headers main_file &gt; new_file
This results in a new line between the two. Is there a way to suppress the new line?
Or maybe another tool ?
Comment: you could do `read.tables`, skipping the first row, and then use `readLines` to get the first row and use the info to give your data frame columns their names.

Here is the accepted answer: Solution 1
$ { echo -n "header1 header2 "; cat file; } &gt;newfile
The -n suppresses the unwanted newline.
Solution 2
Use sed:
$ sed '1s/^/header1 header2 /' file &gt;newfile
Because of the 1, this runs a substitution against the first line (and only the first line) of file.  The caret ^ matches the start of the first line.  The headers are substituted in at the beginning of the line and the rest of the file is left unchanged.
Comment for this answer: Solution 1 did the job. I was not aware of the use of braces and ; in the shell. Thanks.

Here is another answer: In R, you can ignore the first line and then create a new set of names. For example,  use
setNames(read.table(fileName, skip = 1), paste0("header", 1:5))
will read the file and set the new column names matthew91@example.org. Note that the default delimiter for read.table is sep = "", so if it's a csv file you'll need to change that to sep = ",".
Then when you're done you can write the new data set to the same file with write.table, and you won't need to worry about this the next time you use the data.
Comment for this answer: I didnt try this out, yet, but still thanks for pointing out new options of read.table(). Might become useful in the future.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2014:00:10/27/14', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<r><bash><cat>', 'Title': 'add string to the beginning of a text file without new line', 'ViewCount': 760, 'id': 26580116, 'user_AboutMe': '', 'user_AccountId': 3768299.0, 'user_DisplayName': 'Stefan_R', 'user_Reputation': 75.0, 'user_Views': 4.0, 'user_id': 3330491.0}}