I have n number of text files in a folder. Each file will have only one line of text in it. I have to remove the first 500 characters and last two characters from each of the file in the folder.
How could this be done using Powershell?
CodePudding user response:
Use the Substring() method to extract a substring from the line:
# Read single line from file
$line = Get-Content file.txt -TotalCount 1
# Extract a substring starting from index 500 until two characters before the end
$truncatedLine = $line.Substring(500, $line.Length - 502)
# Write line back to file
$truncatedLine |Set-Content file.txt -Force
To run against all txt files in a given folder, use Get-ChildItem to discover the files, then process them one-by-one using ForEach-Object:
Get-ChildItem -Path .\path\to\folder -File -Filter *.txt |ForEach-Object {
$line = $_ |Get-Content -TotalCount 1
$truncatedLine = $line.Substring(500, $line.Length - 502)
$truncatedLine |Set-Content -LiteralPath $_.FullName
}
CodePudding user response:
For example, take out the first 5 numbers and last 2. Array indexes start at 0.
$string = '1234567890'
-join $string[5..($string.length-3)]
678
