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.
-
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.txtDeleting 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 -
Using
findstryou can print lines that don't match, too. So you can do it in several steps, psudocoded like this:findstr pattern input > outputfindstr /v pattern input > input-inversemove /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.
Binary Worrier : Sorry for being an utter pedant, but theres a step between 2 and 3 where you delete "input" file (+1 BTW)Adam Bellaire : @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.Dave Sherohman : True, but the OP's paths start with "d:\". That ain't no unix system. -
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 matchDR : I added examples to my answer. -
Use Sed.
Geoffrey Chetwood : Ok, then tell him how.Baishampayan Ghose : Bah! I gave him a link to a Sed tutorial. Isn't it worth learning Sed? Are we here to spoon-feed people?EBGreen : 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.Baishampayan Ghose : Agreed. But the -1 is unfair :)
0 comments:
Post a Comment