UNIX command

From the below list of the files I need to delete the files where any file name greater than having M1400.

I can use _ as splitter. but not sure what is the exact command.

/files/US> ls -ltr
 
A8399_M1426
A3950_M1374
A3793_M1478
A3793_M1374
A3793_W1374
HA3793_M1426
IA3752_M1426
 

Hello Ramkumar15,

Could you please try following and let me know if this helps.

cat script.ksh
THD=1400
for FILE in *_M*
do
 val=${A##*_M}
 if [[ $val -gt $THD ]]
 then
  echo "Deleting file named " $FILE
  ## rm $FILE
 fi
done

If happy with results then you can remove comment before rm . Hope this helps.

Thanks,
R. Singh

thanks for your response ravi.

I am not sure how this value sets

val=${A##*_M}

I am receiving a bad number below when I executed the script.

house.sh[4]: val: bad number

Hello Ramkumar15,

Please always mention your os details it will help us to guide you more, anyways my command in POST#2 works fine for me, I am using bash.

touch A8399_M1426
THD=1400
for FILE in *_M*
do
 val=${FILE##*_M}
 if [[ $val -gt $THD ]]
 then
  echo "Deleting file named " $FILE
 fi
done
 
Deleting file named  A8399_M1426

As you can see above I have created a test file and then checked the code and it worked fine for me, you could try following too.

for FILE in *_M*
do
 val=`echo $FILE | awk '{sub(/.*_M/,X,$0);print}'`
 if [[ $val -gt $THD ]]
 then
  echo "Deleting file named " $FILE
 fi
done
Deleting file named  A8399_M1426

on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk .

Thanks,
R. Singh

It must be referenced by the iterator variable FILE .

hi ravinder,
its works now.
sorry for not mentioning the OS details.

can you please explain what the below syntax does.

 awk '{sub(/.*_W/,X,$1);print}'

Note that the code RavinderSingh13 provided had an "M" not a "W" in the substitution search pattern (as you requested). But, what that awk script does is to find the first occurrence of the longest string in the 1st field ( $1 ) on an input line ending with the two characters "_" and "W" and, if a match was found, replace that string with the contents of the awk variable X . Since X has not been initialized in this script, it defaults to an empty string. Then, whether or not a change was made, print prints the line.