0

I have a directory containing text files that I need to loop through and remove the first and last line in each file. After that I need to concatenate them and set the output to one file.

My issue is when I loop through the directory it is only manipulating the first file and then stopping. How can I go through each one?

My code:

$path = 'C:\RemoveFirst\*.txt'
$output = 'C:\RemoveFirst\Work.txt'

for ($i = 0; $i -lt $path.Count; $i++) {
    Get-Content $path | Select-Object -Skip 1 | Select-Object -SkipLast 1 | Set-Content $output
}
TheCodeLab
  • 39
  • 2
  • 8

2 Answers2

1

This works too:

$path = 'C:\RemoveFirst\*.txt'
$outfile = 'C:\RemoveFirst\Work.txt'

Get-ChildItem $path|foreach-object{
    Get-Content $_|select-object -Skip 1|select-object -SkipLast 1
} > $outfile
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • 1
    This looks like a good solution! I suggest to replace the aliases by the full command names to make it easier to search for their documentation. Anyone who likes to use aliases can look them up in the docs. – zett42 Mar 11 '21 at 19:29
  • 1
    you're right i'm so used to linux commands that almost forgot about their cmdlet names... – Santiago Squarzon Mar 11 '21 at 19:31
0

This should do the trick:

$path = 'C:\RemoveFirst\*.txt'
$output = 'C:\RemoveFirst\Work.txt'

Get-Item $path | ForEach-Object {

    # Output all except first and last line of current file 
    Get-Content $_ | Select-Object -Skip 1 | Select-Object -SkipLast 1

    ''  # Output an empty line at the end of each file

} | Set-Content $output
  • Get-Item loops over all matching elements when the path contains a wildcard.
  • The ForEach-Object makes the Select-Object statements operate on each file separately. Otherwise they would be applied to the concatenated stream of lines from all files, thus skipping only the 1st line of the 1st file and the last line of the last file.
  • Finally use Set-Content to concatenate all lines into a single file. Alternatively use Out-File, see this post for differences.
zett42
  • 25,437
  • 3
  • 35
  • 72