Reputation: 423
I am bascially trying to replace a single line of text with the entire content of another text file from the command line (linux). Any idea how to do that ?
Upvotes: 2
Views: 357
Reputation: 9154
A variant of sat's answer with sed
, which does not need to read org_file.txt
twice:
sed '/trigger/{
r newfile.txt
d
}' org_file.txt
Or with fewer line breaks:
sed '/trigger/{r newfile.txt
d}' file.txt
There's a drawback: it's not a one-liner, as r
commands interprets everything after it as a filename (more details here).
A workaround was provided by Peter.O (see above link):
sed -f <(sed 's/\\n/\n/'<<<'/trigger/{r new_file.txt\nd}') org_file.txt
Upvotes: 0
Reputation: 14949
You can try this sed
,
sed -e '/trigger/r newfile' -e '/trigger/d' org_file
Here,
newfile
will have a content a content to be insert when trigger
is found in org_file
.
Test:
$ cat > org_file
line 1
line 2
line 3
trigger
line 6
line 7
$ cat > newfile
line 4
line 5
$ sed -e '/trigger/r newfile' -e '/trigger/d' org_file
line 1
line 2
line 3
line 4
line 5
line 6
line 7
Upvotes: 2
Reputation: 41460
Here is one way to do it with awk
awk 'FNR==NR {a[NR]=$0;f++;next} /trigger/ {for (i=1;i<=f;i++) print a[i];next}1' newdata orgfile
It stores the newdata
in an array a
When trigger
is found in orgfile
, replace it by all data from array a
If you need to change a line and know the line number change /trigger/
to FNR==20
Upvotes: 0