MaheshMohan
MaheshMohan

Reputation: 59

How to read a file line by line and create another new file with that content using powershell

I have a file 'abc.txt' that contains below lines.

c:myfilepath\filepath\filepath1\file1.csv  
c:myfilepath\filepath\filepath1\file2.csv  
c:myfilepath\filepath\filepath1\file2.csv  

How to loop through the above file 'abc.txt' and read line by line and create another file called 'xyz.txt' that should contains like below. The file name in the path in 'xyz.txt' should be different, see below (ex. newfile_file1.txt)

c:mynewfile\newfilepath\newfilepath1\newfile_file1.txt (<-This is 
corresponding to file1.csv)  
c:mynewfile\newfilepath\newfilepath1\newfile_file2.txt  
c:mynewfile\newfilepath\newfilepath1\newfile_file2.txt   

I've tried using Get-Content to loop through the file but I just get nothing returned. I'm unclear as to where to put the syntax and how to completely construct it.

Upvotes: 1

Views: 97

Answers (2)

SAS
SAS

Reputation: 4035

This should do it (edited to get file names and paths as requested, and dynamic so the paths in the abc-file are used).

 $f = Get-Content C:\temp\abc.txt # this is the contents-file
 foreach ($r in $f)
 {
     $r2 = (Split-Path $r).Replace("\", "\new") + '\newfile_' + [io.path]::GetFileNameWithoutExtension($r) + '.txt'
     $r2 = $r2.replace(":\", ":\mynewfile\")
     Get-Content $r | Out-File -filepath $r2
 }

Upvotes: 1

Nick
Nick

Reputation: 1208

Assuming all of your file paths start with c:myfilepath\filepath\filepath1, then you can just replace the string then Out-File it.

$File1 = get-content E:\abc.txt
$File1 -replace ('c:myfilepath\\filepath\\filepath1\\', 'c:mynewfile\newfilepath\newfilepath1\newfile_') | 
Out-File E:\xyz.txt

Note the double backslashes \\ which escape the regex.

Upvotes: 0

Related Questions