Tuesday, June 24, 2014

Test command on file size in bash script

My objective was to capture the files locate in a particular path into a file, this is what I did in my bash script.
 # find out all available file
 files=$(ls -1 ${SRC_PATH}/*.txt)
 echo "${files}" > ${TEMP_FILE} 

 # convert the space between each file into newline
 sed 's/ /\n/g' ${TEMP_FILE} > ${PARSE_FILE}
 
 # loop through each file and check the file size is greater than zero
 for file in `cat ${PARSE_FILE}`; do

  file_size=`ls -lah ${file} | awk '{ print $5 }'`
  if [ $file_size -ne 0 ]; then
   echo $file >> "${NICE_FILE}"
  fi
 done
After a few round of review and unit testing on my code, I realize there is a problem where sed command was unable to handle file name with space within it. After a few round of rework, finally I came out a so called "perfect" solution.
 # find out all available file
 files=$(ls -1 ${SRC_PATH}/*.txt)
 echo "${files}" > ${TEMP_FILE} 

 # loop through each file and check the file size is greater than zero
 while read file 
 do
  if [ -s "${file}" ]
  then
   newfile=$(echo "${file}" | sed 's, ,\\ ,g')
    
   echo "${newfile}" >> "${NICE_FILE}"
  fi
 done < ${TEMP_FILE}
No, this is not yet the perfect solution, I'm sure there is always a better one beyond this universe.

No comments: