3

I'm adapting this script to insert one 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 want it to be like this:

REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE

2 Answers 2

8

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"
1
  • sed "1r $1" "$2" made the trick!
    – Lucio
    Mar 7, 2014 at 3:29
3

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .