Monday, April 29, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  8] [ 0]  / answers: 1 / hits: 491  / 1 Year ago, wed, april 12, 2023, 6:28:45

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

More From » bash

 Answers
2

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"

[#26651] Thursday, April 13, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ateact

Total Points: 176
Total Questions: 130
Total Answers: 122

Location: Egypt
Member since Sun, Apr 23, 2023
1 Year ago
;