Computing.Net > Forums > Unix > sed help with variable length file

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Click here to start participating now! Also, check out the New User Guide.

sed help with variable length file

Reply to Message Icon

Name: Linda
Date: September 30, 2003 at 09:46:21 Pacific
OS: SCO5.04
CPU/Ram: 128
Comment:

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.




Sponsored Link
Ads by Google

Response Number 1
Name: James Boothe
Date: October 9, 2003 at 06:07:28 Pacific
Reply:

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'


0

Response Number 2
Name: James Boothe
Date: October 9, 2003 at 06:26:17 Pacific
Reply:

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.


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More


Openbsd boot disc Reading a file line by li...



Post Locked

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


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: sed help with variable length file

help with analog.cfg file on virtual ser www.computing.net/answers/unix/help-with-analogcfg-file-on-virtual-ser/3152.html

Need help with sorting a file www.computing.net/answers/unix/need-help-with-sorting-a-file/6971.html

help with a sed function www.computing.net/answers/unix/help-with-a-sed-function/4297.html