Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Using file to delete content in a text file

    Dear all

    Is it possible to delete a line in a text file using file? For example, suppose i have a text file with the following contents:

    Code:
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the
    industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled
    it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting,
    remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing
    Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including
    versions of Lorem Ipsum.
    How can i delete lines 2 and 3 and leave them blank?

    Thank you.

  • #2
    There is no direct way to delete those lines. However, you could -file read- the file one line at a time, keeping a count of the line number as you go, say in a local macro line_num, and then -file write- each line to a new file (except when inlist(`line_num', 2, 3)). At the end, if you want to, you can then erase the original file and rename the new file with the original file's name.

    Comment


    • #3
      Thank you Clyde Schechter i thought as much. I will try to do what you suggested - although it might be a bit dangerous!

      Comment


      • #4
        Clyde Schechter can you please provide a more specific example as to how to implement the inlist condition? Thank you.

        Comment


        • #5
          So something like this:

          Code:
          file open in_file using my_input_file.txt, read text
          file open out_file using my_output_file.txt, write text
          
          local line_num = 1
          
          file read in_file line
          file write out_file `"`line'"' _n
          
          while r(eof) != 0 {
              local ++line_num
              file read in_file line
              if !inlist(`line_num', 2, 3) { // COPY INPUT LINE TO OUTPUT FOR LINES OTHER THAN 2 AND 3
                  file write out_file `"`line'"' _n
              }
              else { // WRITE A BLANK LINE FOR LINES 2 AND 3
                  file write out_file _n
              }
          }
          file close in_file
          file close out_file
          Note: not tested. Beware of typos or other errors, but this is the gist of it.

          By the way, if you wanted to actually just delete lines 2 and 3, without replacing them with a blank line, just omit the entire -else- block, as writing out a blank line is all it does.

          Comment

          Working...
          X