1

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
-----
tachomi
  • 7,592
Zell
  • 137

2 Answers2

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).

steeldriver
  • 81,074
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
tachomi
  • 7,592