0

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.

Ulrik
  • 1,131
  • 4
  • 19
  • 37

5 Answers5

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

Another:

F=(*/file); D=${F%%/*}
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • 3
    Actually, this will give out the file names. OP wants directory. I think you meant this: `${F%%/*}` =) – savanto Jun 05 '14 at 07:13
0

Try

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

Use / as a separator.

nervosol
  • 1,295
  • 3
  • 24
  • 46
0

You can use the tricky Double quotes! Like so:

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

or

echo "$LIST" | awk -F/ {'print $1'}
Hickory420
  • 131
  • 10
0

You can use builtin read bulletin with -d option:

read -d '/' a < <(echo */file)
echo "$a"
dir1
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • @anubhava yeah, just wanted to edit that, but you were faster. Ok, so this seems like the best solution, but I have a problem with subshell expansion over ssh. I tired escaping parentheses, but it doesn't work. Any suggestions? – Ulrik Jun 05 '14 at 07:29
  • @Ulrik: Following command worked for me on ssh: `ssh localhost "read -d '/' a < <(echo bar/*.pdf) && echo \"$a\""` – anubhava Jun 05 '14 at 07:36
  • be aware - if you're ssh-ing to localhost, you need to be in a different directory in order to see it fail. `(echo */file)` subshell is executed locally and the string is sent over ssh to read. – Ulrik Jun 05 '14 at 07:39
  • Did you try: `ssh localhost "read -d '/' a < <(echo bar/\*.pdf) && echo \"$a\""` command? – anubhava Jun 05 '14 at 07:42
  • `cd /` `ssh localhost "cd foo; read -d '/' a <<<(echo bar/*.pdf); echo \$a"` and watch it fail – Ulrik Jun 05 '14 at 07:43
  • It will only fail if `bar` is not a sub directory in `$HOME`. – anubhava Jun 05 '14 at 07:45
  • ok, it almost works, it gives me the names of all directories containing the file, I just need the name of the first one. – Ulrik Jun 05 '14 at 07:52
  • As I showed above `read -d '/' a < <(echo */file)` gets only part before **very first slash**. – anubhava Jun 05 '14 at 07:55
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/55113/discussion-between-ulrik-and-anubhava). – Ulrik Jun 05 '14 at 07:58
0

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.

lsunny
  • 160
  • 1
  • 2
  • 12