nodejs - Cómo obtener la última parte de dirname en Bash
dirname linux (8)
Supongamos que tengo un archivo /from/here/to/there.txt , y quiero obtener solo la última parte de su dirname to lugar de /from/here/to , ¿qué debo hacer?
Esta pregunta es algo así como THIS .
Para resolver eso, puedes hacer:
DirPath="/from/here/to/there.txt"
DirPath="$(dirname $DirPath)"
DirPath="$(basename $DirPath)"
echo "$DirPath"
Como mi amigo dijo, esto también es posible:
basename `dirname "/from/here/to/there.txt"`
Para obtener cualquier parte de tu camino, podrías hacer:
echo "/from/here/to/there.txt" | awk -F/ ''{ print $2 }''
OR
echo "/from/here/to/there.txt" | awk -F/ ''{ print $3 }''
OR
etc
Forma pura de BASH:
s="/from/here/to/there.txt"
[[ "$s" =~ ([^/]+)/[^/]+$ ]] && echo "${BASH_REMATCH[1]}"
to
Lo opuesto a dirname es basename :
basename "$(dirname "/from/here/to/there.txt")"
Puedes usar el basename aunque no sea un archivo. Quite el nombre del archivo usando dirname , luego use basename para obtener el último elemento de la cadena:
dir="/from/here/to/there.txt"
dir="$(dirname $dir)" # Returns "/from/hear/to"
dir="$(basename $dir)" # Returns just "to"
Una forma más
IFS=/ read -ra x <<<"/from/here/to/there.txt" && printf "%s/n" "${x[-2]}"
Una manera awk de hacerlo sería:
awk -F''/'' ''{print $(NF-1)}'' <<< "/from/here/to/there.txt"
Explicación:
-
-F''/''establece el separador de campo como "/" - imprime el segundo campo pasado
$(NF-1) -
<<<usa cualquier cosa como entrada estándar ( explicación wiki )
Usando la expansión del parámetro Bash, podrías hacer esto:
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)
Esto es más eficiente ya que no se utilizan comandos externos.
Usar las funciones de cadena bash :
$ s="/from/here/to/there.txt"
$ s="${s%/*}" && echo "${s##*/}"
to