views:

461

answers:

4

I am trying to move certain lines from one .txt file to another. These lines all follow a certain pattern. I have been looking at using the find command in a batch file, but this does not delete the line from the original file.

For example:

find \i pattern "d:\example1.txt" >> "d:\example2.txt"

Is there any way to achieve this?

Thanks in advance.

+2  A: 

How about creating two files, then replacing the original?

find \i pattern "d:\example1.txt" >> "d:\example2.txt"
find \i antipattern "d:\example1.txt" >> "d:\example3.txt"
del example1.txt
ren example3.txt example1.txt

Deleting lines from files is hard. Typically, even in a genuine programming environment, you'd be using an extra file here.

Here's a slightly different implementation:

ren example1.txt source.txt
find \i pattern "d:\source.txt" >> "d:\example2.txt"
find \i antipattern "d:\source.txt" >> "d:\example1.txt"
del source.txt
Neil Barnwell
+5  A: 

Using findstr you can print lines that don't match, too. So you can do it in several steps, psudocoded like this:

  • findstr pattern input > output
  • findstr /v pattern input > input-inverse
  • move /y input-inverse input

This should leave you with all lines matching pattern in output, and an input without those lines.

EDIT: Made the last step use move with an option to overwrite, so no need to remove the input before. I guess I (being mainly a Linux person) think of "rename" and "move" as the same thing, and took that overwrite for granted. So, thanks for the heads-up.

unwind
Sorry for being an utter pedant, but theres a step between 2 and 3 where you delete "input" file (+1 BTW)
Binary Worrier
@Binary Worrier: Actually on unix systems, where "mv" is used to rename, if you "mv" an existing file on top of another existing file, the target is automatically replaced, no deletion is necessary.
Adam Bellaire
True, but the OP's paths start with "d:\". That ain't no unix system.
Dave Sherohman
+4  A: 

If you can use external programs, one way would be using awk or sed.

Awk example:

awk /pattern/ { print }

Sed example:

sed '/inverse_pattern/ d' //Deletes lines which do not match
DR
I added examples to my answer.
DR
A: 

Use Sed.

Baishampayan Ghose
Ok, then tell him how.
Geoffrey Chetwood
Bah! I gave him a link to a Sed tutorial. Isn't it worth learning Sed? Are we here to spoon-feed people?
Baishampayan Ghose
Quite often yes. You showed him how to find the answer. While that is better than nothing, this is a Question and Answer site, not a Question and where to go to learn the answer site.
EBGreen
Agreed. But the -1 is unfair :)
Baishampayan Ghose