Search code examples
stringfilepowershellparsingarchive

Parse String | Filename


I got files looking like this:

aaa-xxx-random1.xml
aaa-xxx-random2.xml
aaa-yyy-random3.xml
aaa-zzz-random4.xml
aaa-zzz-random5.xml

How can I parse it in PowerShell to get the second trigram in a variable?

Output expected:

xxx
xxx
yyy
zzz
zzz

In shell that would be:

for f in `ls`; do
  echo $f | cut -d "-" -f 2
done

The goal of this is to create an archive named by the trigram and move all the XML files from the same family into the archive created.


Solution

  • Split the filename at hyphens and pick the second element of the resulting array:

    Get-ChildItem | ForEach-Object { ($_.Name -split '-')[1] }
    

    or (using aliases)

    ls | % {($_.Name -split '-')[1]}