Home > Software engineering >  Duplicate lines in a text file multiple times based on a string and alter duplicated lines
Duplicate lines in a text file multiple times based on a string and alter duplicated lines

Time:11-06

SHORT: I am trying to duplicate lines in all files in a folder based on a certain string and then replace original strings in duplicated lines only.

Contents of the original text file (there are double quotes in the file):

"K:\FILE1.ini"
"K:\FILE1.cfg"
"K:\FILE100.cfg"

I want to duplicate the entire line 4 times only if a string ".ini" is present in a line.

After duplicating the line, I want to change the string in those duplicated lines (original line stays the same) to: for example, ".inf", ".bat", ".cmd", ".mov".

So the expected result of the script is as follows:

"K:\FILE1.ini"
"K:\FILE1.inf"
"K:\FILE1.bat"
"K:\FILE1.cmd"
"K:\FILE1.mov"
"K:\FILE1.cfg"
"K:\FILE100.cfg"

Those files are small, so using streams is not neccessary.

I am at the beginning of my PowerShell journey, but thanks to this community, I already know how to replace string in files recursively:

$directory = "K:\PS"
Get-ChildItem $directory -file -recurse -include *.txt | 
    ForEach-Object {
        (Get-Content $_.FullName) -replace ".ini",".inf" |
            Set-Content $_.FullName
    }

but I have no idea how to duplicate certain lines multiple times and handle multiple string replacements in those duplicated lines.

Yet ;)

Could point me in the right direction?

CodePudding user response:

To achieve this with the operator -replace you can do:

#Define strings to replace pattern with
$2replace = @('.inf','.bat','.cmd','.mov','.ini')
#Get files, use filter instead of include = faster
get-childitem -path [path] -recurse -filter '*.txt' | %{
    $cFile = $_
    #add new strings to array newData
    $newData = @(
        #Read file
        get-content $_.fullname | %{
            #If line matches .ini
            If ($_ -match '\.ini'){
                $cstring = $_
                #Add new strings
                $2replace  | %{
                    #Output new strings
                    $cstring -replace '\.ini',$_
                }
            }
            #output current string
            Else{
                $_
            }
        }
    )
    #Write to disk
    $newData | set-content $cFile.fullname
}

This gives you the following output:

$newdata
"K:\FILE1.inf"
"K:\FILE1.bat"
"K:\FILE1.cmd"
"K:\FILE1.mov"
"K:\FILE1.ini"
"K:\FILE1.cfg"
"K:\FILE100.cfg"
  • Related