Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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

#!/bin/sh

# 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."
    else
        echo "The file does not exist."
    fi
else
   echo "Error: both parameters must be given."
fi

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

The content.txt file:

first_line
second_line

The example.txt file:

REAL_FIRST_LINE
REAL_SECOND_LINE

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:

REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE
share|improve this question

2 Answers 2

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 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
REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE
share|improve this answer

Your Answer

 
discard

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.