I am using sed to insert some lines above a pattern in a file. Example of the file
Stuff Pattern Stuff
Here is the code I am using to split up the file to insert text before
patternline=$(grep -n "Pattern" "/my/file" | cut -f1 -d:) firstcut=$(($patternline -1)) firstpart=$(sed -n 1,"$firstcut"p "/my/file") secondpart=$(sed -n ''"$abspathcomment"',$p' "/my/file") # Indentation intentional as snippet is nested within an IF statement text=$(cat <<EOF Text I want to insert with one leading and two trailing new lines EOF ) echo "$firstpart$text$secondpart" > "/my/file"
I am splitting the file using sed and inserting the text I wish in the middle and finally using cat to output the contents to the same file.
I expect to get (something similar to) the following output for the file
Stuff Text I want to insert with one leading and two trailing new lines Pattern Stuff
But instead I get
Stuff Text I want to insert with one leading and two trailing new linesPattern Stuff
I'm not sure if sed or bash is stripping the newlines. How can I keep them when echoing the result to a file in bash?