Delete a line in a file

I know I can append text to a file, but is there a way to delete specific line from the file?

Thank you

If the line is exactly the same each time, then you could read the file to a variable. Search and replace the line and write to a file again.

Thank you for the suggestion. How do I search variable for lines and delete them?

Thanks!

There's several ways to do this. But let me ask this first: Can you tell us the exact situation you're dealing with? How would you identify the line you want to delete?

The answer to this will help us supply an answer that is tailored to your specific needs.

For example:

  • I want to delete the line that starts with the text "Please Delete th"
  • I want to delete the line that matches exactly "Please Delete this Line"
  • I want to delete the line that contains "Richard"

etc.

Thanks.

Have you already seen these articles in the Keyboard Maestro Wiki?

Dan, thanks for the response.

I want to delete the first and second line from the file.

More specifically, I’m dealing with the following.

I have a text file where every odd line contains a username and every even line contains a password corresponding to the previous username. A script should go through the file and for every login-password combination do some stuff and then delete the first two lines. I need to delete them, so for the next instance of running the script, the username-pass combination will be new and not previously used.

Hi rover233

I have made a test-macro which loops over a text-file. Deleting first 2 lines as it goes a long.
See this video for a demonstration: http://d.pr/v/16s0T

Keyboard Maestro “Example: Delete first 2 lines of file in loop” Macro

Example- Delete first 2 lines of file in loop.kmmacros (6.0 KB)

1 Like

Better would be to read each pair of lines and then perform the script with them, rather that replacing the file each time. But if you want to remove the first two lines of a file, you can use the shell command:

perl -i -ne 'print if $. > 2' '/Users/username/file.txt'

Alternatively, natively in Keyboard Maestro, you would use the Read File action, followed by a Search and replace \A.*\n.*\n with nothing, followed by a Write File action.

2 Likes

Hey @rover233,

So you're deleting the first two lines of each name/password block in a single text file?

Which means you're not just deleting the first two lines in a given file?

Deleting the first two lines of a file is dead easy. Peter's Perl code works nicely, and here's how to do it with sed.

sed -i "" '1,2d' ~/Downloads/test.txt

For jobs like this I usually use AppleScript and the Satimage.osax AppleScript Extension (which must be installed of course).

set fileAlias to alias ((path to downloads folder as text) & "test.txt")
change "\\A(.+\\n){2}" into "" in fileAlias with regexp

You're going to have to provide more information on what you're doing and what the file structure looks like for us to help you more.

-Chris

1 Like