-1

I need to replace the first line of a file with the complete content from another file. Does on see what I'm missing?

$ cat old.txt
---
foo
bar

$ cat append.txt
---
123
<321>

$ cat process.sh
old=old.txt
append=append.txt
sed -i "1s/.*/$append/" $old
cat $old

I'd expect

$ bash process.sh
---
123
<321>
foo
bar

Though instead I got

sed: -e expression #1, char 9: unterminated `s' command

when trying to sed with a variable inside my script

while this one works (without variable) sed -i "1s/.*/loremipsum/" $old

  • Add quotations around the $append variable name. – Raman Sailopal Jul 19 '18 at 12:46
  • @RamanSailopal Thanks. Either: sed -i "1s/.*/"$append"/" $old nor this helps: sed -i '1s/.*/"$append"/' $old – AikenCura Jul 19 '18 at 12:56
  • @AikITYM the shell variable append=$(cat append.txt) . Just so that you know why you are getting this error is because, sed doesn't like newlines on the RHS of a s/// command. – Rakesh Sharma Jul 20 '18 at 5:25
2

To replace the first line of old.txt with the content of append.txt:

$ sed -e '1{ r append.txt' -e 'd;}' old.txt
---
123
<321>
foo
bar

Add -i before the first -e to do the edit in-place in old.txt.

This runs the following short sed script on the given file:

1{                 # we're on the first line
    r append.txt   # read in the whole of the append.txt file
    d;             # delete the current line
}
                   # (implicit print)

On the command line, this is divided into two separate -e expression string since the filename used with the r command must be terminated by a newline (or the end of the current expression string).

  • @don_crissti Oh, blast from the past. – Kusalananda Jul 19 '18 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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