Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm adapting this script to insert file's content into another file. This is what I have now:


# Check if first and second parameters exist
if [ ! -z "$2" ]; then
    STRING=$(cat $1)
    # Check if the supplied file exist
    if [ -e $2 ]; then
        sed -i -e "2i$STRING" $2
        echo "The string \"$STRING\" has been successfully inserted."
        echo "The file does not exist."
   echo "Error: both parameters must be given."

I run it with: ./ content.txt example.txt

The content.txt file:


The example.txt file:


The script's output:

sed: -e expression #1, char 24: unterminated `s' command
The string "first_line
second_line" has been successfully inserted.

And the content of example.txt file remains the same, when I wanna this to be like this:

share|improve this question
up vote 8 down vote accepted

It sounds like you want the r command:

sed "1r $1" "$2"

You might be able to do this with GNU sed:

cat "$1" | sed '2r /dev/stdin' "$2"
share|improve this answer
sed "1r $1" "$2" made the trick! – Lucio Mar 7 '14 at 3:29

In the GNU version of sed, you can use the r (read) command to read and insert the contents of the file directly at a given line address

r filename
    As a GNU extension, this command accepts two addresses.

    Queue the contents of filename to be read and inserted into the output stream
    at the end of the current cycle, or when the next input line is read. Note that
    if filename cannot be read, it is treated as if it were an empty file, without
    any error indication.

    As a GNU sed extension, the special value /dev/stdin is supported for the file
    name, which reads the contents of the standard input.

For example

$ sed '1r content.txt' example.txt
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.