bash - ls command and size of files in shell script -
count=0; #count counting ifs=' ' x in `ls -l $input`; #for loop using ls command a=$(ls -ls | awk '{print $6}') #print[6] sizes of file echo $a b=`echo $a | awk '{split($0,numbers," "); print numbers[1]}'` echo $b if [ $b -eq 0 ] # b size of file count=`expr $count + 1` #if b 0 , count increase 1 one fi echo $count done
i want find 0 size files . using find command. second thing want count number of has 0 size of files using ls command , awk. doesn't true code . mistake ?
your main mistake you're parsing ls
!
if want find (regular) files empty, , if have version of find
supports -empty
predicate, use it:
find . -type f -empty
note recurse in subfolders too; if don't want that, use:
find . -maxdepth 1 -type f -empty
(assuming find
supports -maxdepth
).
if want count how many empty (regular) files have:
find . -maxdepth 1 -type f -empty -printf x | wc -m
and if want perform both operations @ same time, i.e., print out name or save them in array future use, , count them:
empty_files=() while ifs= read -r -d '' f; empty_files+=( "$f" ) done < <(find . -maxdepth 1 -type f -empty -print0) printf 'there %d empty files:\n' "${#empty_files[@]}" printf ' %s\n' "${empty_files[@]}"
with bash≥4.4, use mapfile
instead of while
-read
loop:
mapfile -t -d '' empty_files < <(find . -maxdepth 1 -type f -empty -print0) printf 'there %d empty files:\n' "${#empty_files[@]}" printf ' %s\n' "${empty_files[@]}"
for posix-compliant way, use test
-s
option:
find . -type f \! -exec test -s {} \; -print
and if don't want recurse subdirectories, you'll have -prune
them:
find . \! -name . -prune -type f \! -exec test -s {} \; -print
and if want count them:
find . \! -name . -prune -type f \! -exec test -s {} \; -exec printf x | wc -m
and here, if want perform both operations (count them , save them in array later use), use previous while
-read
loop (or mapfile
if live in future) find
:
find . \! -name . -prune -type f \! -exec test -s {} \; -exec printf '%s\0' {} \;
also see chepner's answer pure shell solution (needs minor tweaking posix compliant).
regarding comment
i want count , delete [empty files]. how can @ same time?
if have gnu find
(or find
supports goodies):
find . -maxdepth 1 -type f -empty -printf x -delete | wc -m
if not,
find . \! -name . -prune -type f \! -exec test -s {} \; -printf x -exec rm {} \; | wc -m
make sure -delete
(or -exec rm {} \;
) predicate @ end! do not exchange order of predicates!
Comments
Post a Comment