Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a line to a file in a shell script?

Tags:

linux

shell

sed

I want to add a row of headers to an existing CSV file, editing in place. How can I do this?

echo 'one, two, three' > testfile.csv

and I want to end up with

column1, column2, column3
one,     two,     three

Changing the initial CSV output is out of my hands.

Any standard command will do. The important thing is the file is edited in place, and the line is inserted at the beginning of the file.

like image 408
user4812 Avatar asked Jan 28 '09 14:01

user4812


People also ask

How do I add a line to a shell file?

Using '>>' with 'echo' command appends a line to a file. Another way is to use 'echo,' pipe(|), and 'tee' commands to add content to a file.

How do I add a line to a file in Unix?

You need to use the >> to append text to end of file. It is also useful to redirect and append/add line to end of file on Linux or Unix-like system.

How do I add a line to a file in Linux?

Append Text Using >> Operator Alternatively, you can use the printf command (do not forget to use \n character to add the next line). You can also use the cat command to concatenate text from one or more files and append it to another file.

How do I add a new line in a bash script?

Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way. However, it's also possible to denote newlines using the “$” sign.


3 Answers

To answer your original question, here's how you do it with sed:

sed -i '1icolumn1, column2, column3' testfile.csv 

The "1i" command tells sed to go to line 1 and insert the text there.

The -i option causes the file to be edited "in place" and can also take an optional argument to create a backup file, for example

sed -i~ '1icolumn1, column2, column3' testfile.csv 

would keep the original file in "testfile.csv~".

like image 63
Matthew Crumley Avatar answered Sep 24 '22 06:09

Matthew Crumley


This adds custom text at the beginning of your file:

echo 'your_custom_escaped_content' > temp_file.csv cat testfile.csv >> temp_file.csv mv temp_file.csv testfile.csv 
like image 21
tunnuz Avatar answered Sep 24 '22 06:09

tunnuz


This doesn't use sed, but using >> will append to a file. For example:

echo 'one, two, three' >> testfile.csv

Edit: To prepend to a file, try something like this:

echo "text"|cat - yourfile > /tmp/out && mv /tmp/out yourfile

I found this through a quick Google search.

like image 21
Scottie T Avatar answered Sep 21 '22 06:09

Scottie T