Select files in a dir that have more than 'n' lines in shell script?

I am trying to select files that have more than 'n' number of lines in a shell script and move them to another directory.

The following command works fine from the command line but not in ashell script,

MY_PATH='/var/www/'
find $MY_PATH -maxdepth 1 -type f -name 'authuser-*' | xargs  wc -l |   awk '{if($1 >= 5) print $1}

But when in a shell script,

files_count=`find $MY_PATH -type f  -name 'authuser-*' | xargs  wc -l | awk '{if($1 > 5) print $2}'`
echo $files_count
exit 1

I am currently using this full command

find /var/www/ -maxdepth 1 -type f -name 'authuser-*'| xargs  wc -l |   awk '{if($1 >= 5) print $2}' | awk '{if($1 !="total") print $1}' | xargs -i basename {} | head -$5 

What could be the problem? is there any other solution to this?

Upvotes: 0

Views: 747

Answers (4)

Ed Morton
Ed Morton

Reputation: 204015

Seems like you're making it MUCH more complicated than necessary:

n=5
for file in authuser-*
do
    (( $(wc -l <"$file") > "$n" )) &&
    mv "$file" wherever...
done

Note that the above will handle files with white space in their names just fine unlike any of the solutions that populate a variable with a list of files.

Upvotes: 1

Vijay
Vijay

Reputation: 67291

The issue is with the find command :

find "$MY_PATH" -type f  -name 'authuser-*'

you missed the double quotes. BTW,the below script works at my place.

#!/bin/sh
mypah='./'
var=`find "$mypah" -name "temp" | xargs nawk '{a[FILENAME]++}END{for(i in a){if(a[i]>5)print i}}'`

echo $var

Upvotes: 0

anubhava
anubhava

Reputation: 785611

Actually I think you throwing in too many piped commands to do a simple job. Consider this for selecting all the files with lines greater than 5:

 find /var/www/ -maxdepth 1 -type f -name 'authuser-*' \
                    -exec awk 'END {if (NR > 5) print FILENAME}' {} \;

Upvotes: 3

P.P
P.P

Reputation: 121407

Did you set your PATH in the script? PATH='/var/www/'

Otherwise, your script will use the system's PATH variable as opposed to the PATH you set. Apart from this, I don't see why your command won't work in the script if it does from the command line.

Also, you shouldn't use PATH for setting your custom path. You can choose a different name like MY_PATH, for example.

Upvotes: 1

Related Questions