2014-04-18 11 views

risposta

12

L'opposto di dirname è basename:

basename "$(dirname "/from/here/to/there.txt")" 
3

Pure modo BASH:

s="/from/here/to/there.txt" 
[[ "$s" =~ ([^/]+)/[^/]+$ ]] && echo "${BASH_REMATCH[1]}" 
to 
+2

Non funziona se il file non ha punti '.'. Non funzionerà se la directory ha il punto '.'. Mantieni la semplicità e usa la barra '/' come delimitatore. – alvits

+0

corretto ora ... – anubhava

+1

Grazie mille @Akshay – anubhava

57

È possibile utilizzare basename anche se non è un file. Togliere il nome del file utilizzando dirname, quindi utilizzare basename per ottenere l'ultimo elemento della stringa:

dir="/from/here/to/there.txt" 
dir="$(dirname $dir)" # Returns "/from/hear/to" 
dir="$(basename $dir)" # Returns just "to" 
+1

il comando '$ dir = "$ (dirname $ dir)"' non funziona per me, ma 'dir = "$ (dirname $ dir)" "funziona bene. –

+0

Non avrei dovuto avere il dollaro di fronte a 'dir' quando lo sto impostando. –

+0

Sì, ora tutto funziona correttamente. Grazie :) –

15

Utilizzando bash funzioni stringa:

$ s="/from/here/to/there.txt" 
$ s="${s%/*}" && echo "${s##*/}" 
to 
2

un altro modo

IFS=/ read -ra x <<<"/from/here/to/there.txt" && printf "%s\n" "${x[-2]}" 
+0

Più semplice da usare: 'printf"% s \ n "" $ {x [-2]} "'. –

+0

@gniourf_gniourf, hai ragione, grazie. Modificato – iruvar

1

An awk modo di farlo sarebbe:

awk -F'/' '{print $(NF-1)}' <<< "/from/here/to/there.txt" 

Spiegazione:

  • -F'/' set campo di separazione come "/"
  • stampare il secondo ultimo campo $(NF-1)
  • <<< usa nulla dopo come standard input (wiki explanation)
1

Questa domanda è simile a THIS.

Per la soluzione che si può fare:

DirPath="/from/here/to/there.txt" 
DirPath="$(dirname $DirPath)" 
DirPath="$(basename $DirPath)" 

echo "$DirPath" 

Come il mio amico ha detto che questo è possibile vedere:

basename `dirname "/from/here/to/there.txt"` 

Al fine di ottenere qualsiasi parte del vostro percorso si potrebbe fare:

echo "/from/here/to/there.txt" | awk -F/ '{ print $2 }' 
OR 
echo "/from/here/to/there.txt" | awk -F/ '{ print $3 }' 
OR 
etc 
0

Utilizzando Bash parameter expansion, è possibile effettuare le seguenti operazioni:

path="/from/here/to/there.txt" 
dir="${path%/*}"  # sets dir  to '/from/here/to' (equivalent of dirname) 
last_dir="${dir##*/}" # sets last_dir to 'to' (equivalent of basename) 

Questo è più efficiente poiché non vengono utilizzati comandi esterni.

+0

Ho appena provato questo. Su FreeBSD qui sono i miei risultati: Codice:! #!/Bin/sh cd/var/svn/repos percorso = "$ 1" echo "$ {path}" dir = "$ {path%/*} " echo" $ {dir} " actual =" $ {dir ## * /} " echo" $ {actual} " --------------- ------------------------- Risultati: $ ./makerepo.sh/var/test /var/test /var var $ ------------------------------------ Fai l! Scusate. Sembrava un buon metodo ma non una risposta corretta. –

+0

Non importa. Ho appena realizzato cosa è successo! –

Problemi correlati