I have thousands of text files and would like to know how to check if a particular file is empty. I am reading all the files using this line of code
Y<-grep(\
Use the following code to check if a file in the system is empty or not before uploading it.
my_file<-readLines(paste0("<path of file/file name.extension>"))
my_file=="" #TRUE - means the file is empty
For a functional approach, you might first write a predicate:
file.empty <- function(filenames) file.info(filenames)$size == 0
And then filter the list of files using it:
Filter(file.empty, dir())
You can use file.info for that:
info = file.info(filenames)
empty = rownames(info[info$size == 0, ])
Incidentally, there’s a better way of listing text files than using grep
: specify the pattern
argument to list.files
:
list.files(pattern = '\\.txt$')
Notice that the pattern needs to be a regular expression, not a glob – the same is true for grep
!
find . -empty
or
find . -empty |awk -F\/ '{print $FN}'
If you want to limit just txt files:
find . -empty -name "*.txt"
If you want only asci files (not just .txt)
find . -empty -type f
put it all together:
find . -empty -type f -name "*.txt" |awk -F\/ '{print $NF}'