I have folder with some .txt files. I want to search through the files and find lines where this pattern is part of the line: BDAS. The line3 could look like this:
This is a line number 1 with BDAS-1111
This is a line number 2 with BDAS-1111
This is a line number 3 with BDAS-2222
BDAS-1111 and BDAS-2222 should both be recorded once and the result (filename, BDAS-code) should be written to a .csv file.
I have been able to parse line and filename to a .CSV file, so the content will be this:
This is a line number 1 with BDAS-1111;filename.txt
This is a line number 3 with BDAS-2222;filename.txt
But please please please do not use backticks. That’s the worst style / habbit you can have for Powershell scripts. Especially when you place them after the pipe symbol … that’s a line continuation charachter anyway.
Thanks for your (quick) reply - I’ll try it out as soon as possible. So ‘$_.Matches.Value’ will return ‘BDAS-’ plus whatever comes after that (ie BDAS-1111, BDAS-2222)? That was exactly what I was looking for:-)
I haven’t been able to find any documentation for your -Pattern string ‘\BDAS-\d{4}’? What does ‘\d{4}’ mean?
Aha, ‘d{4}’ is a regular expression, and search for all occurence of ‘BDAS-’ followed by a 4-digit number:-) I have changed the script a little to this:
[quote quote=198326]It works like a charm:-)
…
I’m searching for occurences of both ‘BDAS-’ and ‘WK-’ followed by a number with 1-4 digits. The result is piped to a CSV-file[/quote]
I’m glad I could be of help and I’m proud that you figured out by yourself. Great. You can simplyfy your pattern a little bit like this:
I’m struggling with a little modification. Each line starts with a date in format DDMMYY. But how can I get this info into My csv file? Some kind of “copystring” would maybe Do the trick, but I dont know what string to copy from?
Now you have to learn about named groups in regular expressions to understand what we just did here with the regex pattern.
And I used a PSCustomObject to make the code somewhat easier to read. Here you can read more about it:
I added some additional properties for convinience such as LineNumber, the actual DateTime from match of DayMonthYear string (ddMMyy) so you can sort it properly for the date and the complete line just for reference or to check. Of course you can remove them if you don’t need them.
Hy Olaf
This works just like a charm:-) I knew about the PSCustomObject but have never used it. And the regex is just awsome:-) I needed to iterate the .txt files in a folder, so my script ended up like this:
I assumed that from the code you posted previously. But you don’t need another loop for that. You can provide a path with a wildcard in it for Select-String just like I showed in my code suggestion. That should even be a little faster.