How can I search for a string that wraps on to the next line and
then replace the carriage return with nothing so that the line no longer
wraps on to the next line?
blah blah blah...bl
ah blah blah...bla
h blah blah...blah
blah blah blah bl
ah blah blah blah
In the above text, each time the line wraps it adds a space at the beginning of the next line. I want to search for <CR><space> and replace it with nothing so the line no longer wraps and looks like this:
blah blah blah...blah blah blah...blah blah blah...blah blah blah blah blah blah blah blah
You could use awk or sed:
sed -e :a -e '$!N;s/\n //;ta' -e P -e D infile
$!N says to fetch the Next line into the current buffer for the specified range of lines, which in this case is each line that is NOT the last line ($ means last line and ! means NOT).
Possibly a clearer example of a command preceded by a qualifying line
number or range of lines would be:
sed 2,4d ?(delete lines 2-4)
sed 2,4!d (delete all but lines 2-4)
ta is a conditional (Test) branch to label a. From the man page:
Branch to the : command bearing the label if any substitutions have been made since the most recent reading of an input line or execution of a t.
ba would be an unconditional Branch to label a.
Calling the next line into the buffer allows looking at multiple lines at once. With multiple lines in the buffer, this allows me to include the delimiting newline character(s) in my edits. In this case, I am deleting any newline-followed-by-space strings.
The logic depends upon always keeping the last line in the buffer (in case the next line needs to be joined to it). When I delete the newline character and thus join two lines into one, I now have just one line in the buffer, and I cannot output that line yet because the next line might also need to be joined. Thus, the loop is required. As long as changes are made (newline characters being deleted), it will keep looping and pulling more lines into the buffer until finally no changes are made, meaning I have two lines in the buffer, so I can fall out of the loop which will output the first of the two lines.
Have a Unix Problem
Do you have a UNIX Question?
Unix Books :-
UNIX Programming, Certification, System Administration, Performance Tuning Reference Books
Return to : - Unix System Administration Hints and Tips
(c) www.gotothings.com All material on this site is
Every effort is made to ensure the content integrity. Information used on this site is at your own risk.
All product names are trademarks of their respective companies.
The site www.gotothings.com is in no way affiliated with or endorsed by any company listed at this site.
Any unauthorised copying or mirroring is prohibited.