简体   繁体   中英

bash: how to display the name of the first directory that contains a certain file

I have this:

ls */file
dir1/file dir2/file dir3/file

But I need just the first directory name, like this: dir1

I did this:

IFS="/" read foo bar <<< "$(ls */file 2>/dev/null)"
echo $foo
dir1

And it works, but now I have a problem with subshell expansion over ssh . Is there a more elegant way (without subshells or sed ) to do this?

If not, I'll then post a question regarding a completely different issue - expanding subshells over ssh .

for F in */file; do
    D=${F%%/*}
    break
done

Another:

F=(*/file); D=${F%%/*}

Try

ls */file | cut -d"/" -f1

Use / as a separator.

You can use the tricky Double quotes! Like so:

LIST=`ls */file`
echo "$LIST" | cut -d/ -f1

or

echo "$LIST" | awk -F/ {'print $1'}

You can use builtin read bulletin with -d option:

read -d '/' a < <(echo */file)
echo "$a"
dir1

If you just need the name of the folder you can use :

$ls -1 | awk 'NR==n'

Where n=1 is the first directory, you can change the value of n to get the nth Directory.

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