Z
Z
zenondd2021-04-27 14:14:48
PowerShell
zenondd, 2021-04-27 14:14:48

How to search and copy a block of lines by keyword in *.txt?

Good day!

There is a text file with many blocks of lines. I need to save in a separate file all the blocks by the keyword in the first line of the block.

For example, the file in.txt:

[Object_parametr]
First
Second
Third
Forth

[Second_parametr]
First
Second
Third
Forth

[Object]
First
Second
Third
Forth

The keyword "parametr" should be copied to the file out.txt:

[Object_parametr]
First
Second
Third
Forth

[Second_parametr ]
First
Second
Third
Forth

I believe that this can be done using BAT / PS, but please tell me how?

Along the way, the question is: is it feasible using C tools?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Eugene, 2021-04-27
@zenondd

I wrote a Powershell script that outputs the information you need to a file
$file = get-content "C:\temp\in.txt"
$out = Foreach ($str in $file)
{
If($str -match "\[. *\]")
{
If ($str -match "parametr")
{
$flg = 1
}
Else {$flg=0}
}
If ($flg -eq 1)
{
$str
}
}
$out | Out-File -FilePath C:\temp\
out.txt Please do not find fault, I write as best as I can =))

R
Romses Panagiotis, 2021-04-27
@romesses

What is needed there? Reading and writing files, loop, pattern matching. Just.
Take some scripting language and go.

M
MaxKozlov, 2021-04-27
@MaxKozlov


if the number of lines in each block is constant, Select-String with the -Context parameter is suitable for powershell parsing .
If not, loop manually

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question