从给定路径中提取目录名称并将其匹配

时间:2017-01-09 23:03:36

标签: bash

从路径中提取所有目录名称并将其与作为参数提供的目录名称进行比较的最佳方法是什么:

find_dir() {
path='/download/1/2/3/4/5/6'
for dir in logic ${path}
  if [ dir = $1 ]; then
      echo "Directory $1 found in $path"
      exit(0)
  else
      pass
  fi
echo "Directory $1 not found in $path"
}

结果:

pompt$ find_dir 4
Directory 4 found in /download/1/2/3/4/5/6

pompt$ find_dir 8
Directory 8 not found in /download/1/2/3/4/5/6

2 个答案:

答案 0 :(得分:0)

只需在/中使用正则表达式匹配包装目录名称(注意if [[ $dir =~ .*/$1/.* ]] ; then语法,双括号,分号前的空格和正则表达式测试的=~

#!/bin/bash
find_dir() {
path='/download/1/2/3/4/5/6'
for dir in logic ${path}
 do
  if [[ "$dir" =~ .*/$1/.* ]] ; then
      echo "Directory $1 found in $path"
      exit 0
  fi
 done
echo "Directory $1 not found in $path"
}

find_dir 8
find_dir 4

结果:

Directory 8 not found in /download/1/2/3/4/5/6
Directory 4 found in /download/1/2/3/4/5/6

注意:我保留了for循环,但logic参数没有任何意义......

答案 1 :(得分:0)

你可以这样做:

#!/usr/bin/env bash

find_dir() {
    path='/download/1/2/3/4/5/6'
    lastdir=$(rev <<< "$path" | cut -f1 -d/)
    n=1
    while [[ $dir != $lastdir ]]; do
        dir=$(cut -f$n -d/ <<< "$path")
        ((n++))
        if [[ $dir == $1 ]]; then
           echo "Directory $1 found in $path"
           exit 0
        fi
    done
    echo "Directory $1 not found in $path"
}