R: get a list of short file names (filenames) for all files in a directory

2.6k Views Asked by At

Problem

list.files(Path) returns a vector of names of files in the directory Path. This is great, but I need a vector of short file names (SFN). For instance, the SFN for WageDataFile.csv is WAGEDA~1.csv (if there is no other file in the directory with the stem "WageDa"). The SFN is also called the 8.3 filename.

Desired solution

Specifically, I am hoping for a function that will pull the SFN from the OS rather than reconstruct it from the output of list.files() (but methods to reconstruct the SFN from the output of list.files() are welcome, too).

Code for reproducible case

This will create a set of files at "E:/FileNameTest" with variable name lengths:

setwd("E:/FileNameTest")
library(stringi)
nFiles = 12
minNameLength = 2
maxNameLength = 12
set.seed(1)
FileNames = 
    stri_rand_strings(nFiles, 
                length=sample(minNameLength:maxNameLength,nFiles,replace=T), 
                '[A-Za-z0-9]')
file.create(FileNames)

Here is the content of FileNames:

 [1] "lUizNmvDe7"   "GN0Nr"        "LTbUBpfn"     "6i"           "Poe"          "mYWm1Tjg"    
 [7] "TrRF46JWfPuI" "SKe"          "FTl5sLqLKTtr" "OmxQ"         "iO"           "KkCi7F" 

Here is the list of SFN that I need from those file names (edit: the names that were shortened should be in all caps):

[1] "6i"       "FTL5SL~1" "GN0Nr"    "iO"       "KkCi7F"   "LTbUBpfn" "LUIZNM~1" "mYWm1Tjg" "OmxQ"    
[10] "Poe"      "SKe"      "TRRF46~1"
1

There are 1 best solutions below

0
On

Here is a solution (based on a comment from MrFlick) that may rely on invalid assumptions about the output of dir. Specifically, I assume that the header and footer of the output always take up 5 and 2 lines, respectively, and that the width of fields in the dir /x/a:-d output is always constant.

library(stringr)
FileList = shell("dir /x/a:-d", intern=T)
FileList = FileList[6:(length(FileList)-2)]
SFN = str_replace(str_sub(FileList, 39, 46), "        ", "")
Name = str_sub(FileList, 52, -1)
NameList = ifelse(str_length(SFN)>0, SFN, Name)