1

I want to remove all the images which has the name without the "@2x", and I want to write a shell script to finish this. This is what I do:

#!/bin/bash

dir="/Users/me/Workspace/"
cd $dir
all_pngs=`find . -name "*.png" | sort -u`
for png in $all_pngs
do
    #    echo "$png"
    #get the dirname
    dirname=`dirname $png`
    #get the filename without dir
    filename=`basename $png`
    #get name without suffix
    name=`echo "$filename" | cut -d '.' -f1`
    realname=`echo "$name" | grep -v "@2x"`
    if [ -n $realname ]; then
        echo "$realname"
    fi

done

My problem is that I don't know how can I find the name without the "@2x".

user3386109
  • 34,287
  • 7
  • 49
  • 68
Yue Liu
  • 213
  • 2
  • 9
  • This isn't the primary issue with the script, but see [this](http://stackoverflow.com/a/7039579/3076724) if you want to loop over `find` output safely (i.e. won't mangle filenames with spaces, newlines, etc...) – Reinstate Monica Please Jun 27 '14 at 04:41

2 Answers2

1

I'm not really sure what you're trying to do with the rest of your script, but just something like this should work

find /Users/me/Workspace/ -type f -name '*.png' \! -name '*@2x*' -exec echo rm '{}' +

Remove the echo when you're confident that's what you want.

Since the ! exp has a higher precedence in find than the implied -a between tests and actions the above gets treated as

find /Users/me/Workspace/ (-type f) AND (-name '*.png') AND (! -name '*@2x*') AND (-exec echo rm '{}' +)
Reinstate Monica Please
  • 11,123
  • 3
  • 27
  • 48
  • there is another problem, the references to the removed files become error(it becomes red), then how to delete the error references in Xcode? – Yue Liu Jun 27 '14 at 05:48
  • @YueLiu Not sure, haven't used `xcode` in a while. [This question](http://stackoverflow.com/q/5545171/3076724) is somewhat on point, though might be worth asking again if you don't find a better solution. – Reinstate Monica Please Jun 27 '14 at 17:25
  • I had found a solution with this problem. I just delete the folder which the deleted files belongs to, and then added it again. – Yue Liu Jun 30 '14 at 06:34
0

You have used many unwanted operation in your for loop which are not necessary( but exactly any purpose of it?). You need simple logic in your for..loop as below. OR in one sentence you can use nice answer given by @BroSlow

You can check if your file name contain "@2x" or not like

if [[ $png = *@2x* ]] //Yes it contain "@2x"
then
    echo "File name contain @2x keep as it is."
else
    //remove file // rm -f $png
fi

Using grep

if grep -o "@2x" <<<"$png" >/dev/null
then
    echo "File name contain @2x keep as it is."
else
    //remove file // rm -f $png
fi
Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73