1

This question already has an answer here:

file contents:

# cat file.txt 
-----
MATCH
-----
MATCH
-----
MATCH
-----

# cat text.txt 
add this text file
before first match

sed commands:

# sed '0,/MATCH/r text.txt' file.txt
-----
add this text file
before first match
MATCH
add this text file
before first match
-----
MATCH
-----
MATCH
-----

# sed '0,/MATCH/i prependme once' file.txt
prependme once
-----
prependme once
MATCH
-----
MATCH
-----
MATCH
-----

I'm trying to merge these commands somehow to get the following output:

-----
add this text file
before first match
MATCH
-----
MATCH
-----
MATCH
-----

marked as duplicate by don_crissti, Networker, Stephen Harris, heemayl, sam Jul 16 '16 at 19:12

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4

With ed instead of sed

ed -s << EOF file.txt
0,/MATCH/-1 r text.txt
,p
q
EOF

or as a one-liner

printf '0,/MATCH/-1 r text.txt\n,p\nq' | ed -s file.txt
-----
add this text file
before first match
MATCH
-----
MATCH
-----
MATCH
-----

(replace ,p by w for in-place editing).

1

Try this

$ sed '0,/MATCH/ s/MATCH/add this text file\nbefore first match\nMATCH/' file.txt

or just use other sed expression for your output

$ sed '0,/MATCH/i prependme once' file.txt | sed 1d

for adding file content

$ sed -e '0,/MATCH/s/MATCH/$(cat text.txt)\nMATCH/' file.txt

Other possible solution using ----- as your matching string

$ sed '0,/-----/r text.txt' file.txt

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