1

I would like to replace the contents between $Elements$ and $EndElements$ in text file, f1, with the data from another file, f2.

The contents of f1 is given simply by

$Elements$
3
1
5
7
$EndElements$

And the contents of f2 is given as

1 65 71
2 32 87
3 39 98
4 41 63

What I would like to get at the end is:

$Elements$
1 65 71
2 32 87
3 39 98
4 41 63
$EndElements$

For this I tried some sed code from stackexchange pages(well I copied the code and do not have the window open anymore so I can not provide the direct link, sorry)

lead='^\$Elements\$$' 
tail='^\$EndElements\$$'
# f2 is the file where the information
# to replace is kept in 
sed -e "/$lead/,/$tail/{ /$lead/{p; r insert_file
    >         }; /$tail/p; d }"  f2

which does not work, basically doing nothing.

  • Are $Elements$ and $EndElements$ the first and last lines in the first file? – Inian Jun 7 '17 at 7:18
2

With ed(1):

echo -e '/\$Elements\$/+1,/\$EndElements\$/-1d\n.-1r f2\nw' | ed -s f1

In detail:

  • /\$Elements\$/+1,/\$EndElements\$/-1 matches the lines between $Elements$ and $EndElements$
  • d deletes said lines
  • .-1 is now the line above $EndElements$
  • r f2 reads file f2
  • w writes the results.
2
sed -e "
   /$lead/,/$tail/!b
   //!d
   /$lead/r f2
" f1

Results

$Elements$
1 65 71
2 32 87
3 39 98
4 41 63
$EndElements$

Working

  1. First we select the proper range by using the , comma operator.
  2. All the lines that don't fall within this range are printed as is, via the b command, that branches control to the end of the sed code for this line(s).
  3. The body of the range are deleted, //!d since we intend to replace the body of the range with the custom file, f2.
  4. The lead line when encountered, reads in the contents of the custom file, f2 into the printing queue (which is not the same as the pattern space, mind you.)
  5. When the control reaches the end of sed code, the contents of pattern space, holding the lead line as emptied out onto stdout and AFTER this event, are the contents of the queue are emptied out onto stdout.

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.