Reverse the order of lines in a text file while preserving the contents of each line: Difference between revisions

→‎{{header|REXX}}: added a 2nd version which if faster and uses less memory (storage).
(→‎{{header|REXX}}: added a 2nd version which if faster and uses less memory (storage).)
Line 247:
 
=={{header|REXX}}==
=== version 1 ===
This will work for all REXXes,   but it reads all the file's lines/records into memory (storage or buffers).
 
No assumptions were made concerning line/record termination,   as REXX takes care of that.
<lang rexx>/*REXX pgm reads a file, and displays the lines (records) of the file in reverse order. */
parse arg iFID . /*obtain optional argument from the CL.*/
if iFID=='' | iFID=="," then iFID='REVERSEF.TXT' /*Not specified? Then use the default.*/
call lineout iFidiFID /*close file, good programming practice*/
do #=1 while lines(iFID)>0 /*read the file, one record at a time. */
 
do j@.#=1 while lineslinein(iFID)>0 /*readassign thecontents file,of onea record atto a timearray. */
@.j= linein(iFID) end /*assign contents of a record to array.#*/
recs= # - 1 end /*j# will be 1 more ('cause of DO loop)*/
recs= j - 1 /*J will be 1 more ('cause of DO loop)*/
do k=recs by -1 for recs /*process array (@.k) in reverse order.*/
say @.k /*display a record of the file ──► term*/
end /*k*/
call lineout iFidiFID /*close file, good programming practice*/</lang>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 269 ⟶ 271:
"Diplomacy is the art of
</pre>
 
=== version 2 ===
This will work for all the following REXXes &nbsp; (and perhaps other REXXes as well):
::* &nbsp; Regina REXX
::* &nbsp; R4 REXX
::* &nbsp; ROO REXX
::* &nbsp; CMS REXX
<lang>/*REXX pgm reads a file, and displays the lines (records) of the file in reverse order. */
parse arg iFID . /*obtain optional argument from the CL.*/
if iFID=='' | iFID=="," then iFID='REVERSEF.TXT' /*Not specified? Then use the default.*/
call lineout iFID /*close file, good programming practice*/
options noFast_lines_BIF_default /*an option just for Regina REXX. */
recs#= j - 1 lines(iFID) /*J#: willthe benumber 1of morelines ('causein ofthe DOfile. loop)*/
do j=# by -1 for # /*read file (backwards), from bot──►top*/
@.j= linein(iFID, j) /*assign contents of a record to array.*/
say @.j /*display a record of the file ──► term*/
end /*j*/
call lineout iFID /*close file, good programming practice*/</lang>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
=={{header|Ring}}==