Question

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.

Was it helpful?

Solution

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

Another:

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top