Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I have the sed commands but need help stringing them together correctly. Reading a variable length file where the last line is only ^Z. Need to change the preceding line ending in ^M to ^M^Z.

The following code will pass a file (with no changes) by keeping the last two lines in its buffer. The N appends the second line, and the P and D will print and delete the first of the two lines.
sed '$!N;P;D'
This provides a one-line look-ahead so that, when we know we are at the last line, we can change the next-to-last line. To prevent our substitution from changing both the previous AND last line (which are both in the buffer), the search pattern will terminate with the embedded newline character. With two lines in the sed buffer, there is only one embedded newline, which can be indicated with \n. The very end of the buffer can be indicated with $.
In the following code, I use the letters M and Z. Per your post, you will need to use Ctrl-M and Ctrl-Z instead. I tested successfully with the control characters. I was not able to enter a Ctrl-M interactively, so I used vi.
sed '$!N;$s/\(M\)\(\n\)/MZ\2/;P;D'

And since sed can make substitutions to a targeted line number, as in:
sed 27s/foo/bar/ infile
another approach could be to get the line count minus one of the input file, then use that (as a variable) in your sed command.

![]() |
Openbsd boot disc
|
Reading a file line by li...
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |