简体   繁体   中英

Printing the name of each file with certain extension

how can I print out the name of each file in a certain directory with a specific extension?

Here's what I have so far:

#!/bin/sh

DIR="~/Desktop"
SUFFIX="in"

for file in $DIR/*.$SUFFIX
do
    if [ -f $file ]; then
    echo $file
    fi  
done

Unfortunately it doesn't work.

What's wrong with it?

In your DIR="~/Desktop" the "~" not expanded, because it is in "". remove the "". DIR=~/Desktop

You could use find with -type f

#!/bin/sh
DIR="~/Desktop"
SUFFIX="in"
find "$DIR" -maxdepth 1 -type f -name "*.${SUFFIX}" -exec somecommand {} \;

For your information: "file" in Unix systems is typically the name of a command.

Its purpose is to analyze the files given as argument and infer the format. Example:

$ file entries.jar 
entries.jar: Zip archive data, at least v2.0 to extract
for file in `ls $DIR/*.$SUFFIX`

注意ls和反引号

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM