Bash variable containing file wildcard

2019-09-08 17:01发布

问题:

I have a variable containing wildarded file descriptors:

FORMATS='*.mobi *.pdf *.txt *.epub *.lit'

It gets expanded with the appropriate files if I write

echo $FORMATS

and retains its string value if i quote it

echo "$FORMATS"

Now, I need to manipulate it as a string and I do this.

SUBST=`echo "$FORMATS" | sed "s/$1//"`

The problem is that within `` the files get expanded anyway. How to prevent this? Thanks.

回答1:

No, it doesn't get expanded!

What you are probably doing is using SUBST without quotes (eg: echo $SUBST) and then it gets expanded... use "$SUBST".



回答2:

This might work for you:

cd /tmp/formats
touch a.mobi b.pdf c.txt e.epub f.lit
a='*.mobi *.pdf *.txt *.epub *.lit'
echo "$a"
*.mobi *.pdf *.txt *.epub *.lit
echo $a  
a.mobi b.pdf c.txt e.epub f.lit
b=pdf
c=$(echo "${a/\*.$b}")
echo "$c"
*.mobi  *.txt *.epub *.lit
echo $c  
a.mobi c.txt e.epub f.lit


回答3:

without seeing more of your code I can only guess that maybe you want to do something like this:

:this is shell only - no other tools needed

for FILE in *.mobi *.pdf *.txt *.epub *.lit ; do
    case "$FILE" in
        "*.mobi"|"*.pdf"|"*.txt"|"*.epub"|"*.lit")continue;;
        *)echo "${FILE//$1/}";;
    esac
done

presumably you would mv or cp the file to the new file name???



标签: bash shell