简体   繁体   中英

Bash one-liner for isolating directory name

In Bash, v.4.3.11(1) I have this sample code:

#!/bin/bash

dir=("/home/user/Documents/" "/home/user/Music/" "/home/user/Videos/" \
"/home/user/Photos/")

baseDir="/home/user/"

for i in "${!dir[@]}"
do
    niceName=${dir[$i]#"$baseDir"}  # removes baseDir from front part
    printf "%s\n" "${niceName%"/"}"  # also removes trailing slash from end
done

Is there a way to combine the two commands in one and have only the printf within the for loop? (preferably without resorting to awk or sed, but ok, if inevitable).

I have tried various combinations but I am ending up with "bad substitution" errors. For example, printf "%s\\n" "${niceName=${dir[$i]#"$baseDir"%"/"}" is not working for me.

Here is a simpler version.

#!/bin/bash
dir=("/home/user/Documents/" "/home/user/Music/" "/home/user/Videos/" "/home/user/Photos/")

for d in "${dir[@]}"
do
  basename "$d"
done

Please note the argument to basename needs to be quoted, or else directory names with some characters (such as spaces) will cause problems.

The inside of the loop could also be replaced by the builtins-based solutions below (faster and without external dependencies) :

  d="${d%/}"
  echo "${d##*/}"

If you're looking for a one-liner using substitution, this'll work:

dir=("/home/user/Documents/" "/home/user/Music/" "/home/user/Videos/" \
"/home/user/Photos/")
baseDir="/home/user/"
dir=("${dir[@]%/}")    ## This line removes trailing forward slashes
printf "%s\n" "${dir[@]#$baseDir}"

You could use basename which returns just the base file name. In this case, your file is the directory.

#!/bin/bash
dir=("/home/user/Documents/" "/home/user/Music/" "/home/user/Videos/" "/home/user/Photos/")

for i in "${!dir[@]}"
do
  echo $( basename ${dir[$i]})
done

As far as I know bash does not handle "double parameter expansion" (I believe zsh does). However, you can hack together a solution like this:

dir=("/home/user/Documents/" "/home/user/Music/" "/home/user/Videos/" "/home/user/Photos/")
trunk=/home/user/

echo $(dir=( "${dir[@]##${trunk}}" ); echo "${dir[@]%/}")

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