查找命令,枚举输出并允许选择?

Leo*_*sev 10 bash find files

当我使用时find,它经常会发现多个结果,例如

find -name pom.xml
./projectA/pom.xml
./projectB/pom.xml
./projectC/pom.xml
Run Code Online (Sandbox Code Playgroud)

我经常只想选择一个特定的结果,(例如edit ./projectB/pom.xml)。有没有办法枚举find输出并选择一个文件传递给另一个应用程序?喜欢:

find <print line nums?> -name pom.xml
1 ./projectA/pom.xml
2 ./projectB/pom.xml
3 ./projectC/pom.xml

!! | <get 2nd entry> | xargs myEditor
Run Code Online (Sandbox Code Playgroud)

?

[编辑] 我在提到的一些解决方案中遇到了一些特殊的错误。所以我想解释一下重现的步骤:

git clone http://git.eclipse.org/gitroot/platform/eclipse.platform.swt.git
cd eclipse.platform.swt.git
<now try looking for 'pom.xml' and 'feature.xml' files>
Run Code Online (Sandbox Code Playgroud)

[编辑] 解决方案 1 到目前为止,如果我将“nl”(枚举输出)、head & tail 组合成函数并使用 $(!!),它们似乎可以工作。

IE:

find -name pom.xml | nl   #look for files, enumirate output.

#I then define a function called "nls"
nls () {
  head -n $1 | tail -n 1
}

# I then type: (suppose I want to select item #2)
<my command> $(!!s 2)

# I press enter, it expands like: (suppose my command is vim)
vim $(find -name pom.xml |nls 2)

# bang, file #2 opens in vim and Bob's your uncle.
Run Code Online (Sandbox Code Playgroud)

[编辑] 解决方案 2 使用“选择”似乎也很有效。前任:

  findexec () {
          # Usage: findexec <cmd> <name/pattern>
          # ex: findexec vim pom.xml
          IFS=$'\n'; 
          select file in $(find -type f -name "$2"); do
                  #$EDITOR "$file"
                  "$1" "$file"
                  break
          done;  
          unset IFS
  }
Run Code Online (Sandbox Code Playgroud)

Dop*_*oti 16

使用bash的内置select

IFS=$'\n'; select file in $(find -type f -name pom.xml); do
  $EDITOR "$file"
  break
done; unset IFS
Run Code Online (Sandbox Code Playgroud)

对于评论中添加的“奖金”问题:

declare -a manifest
IFS=$'\n'; select file in $(find -type f -name pom.xml) __QUIT__; do
  if [[ "$file" == "__QUIT__" ]]; then
     break;
  else
     manifest+=("$file")
  fi
done; unset IFS
for file in ${manifest[@]}; do
    $EDITOR "$file"
done
# This for loop can, if $EDITOR == vim, be replaced with 
# $EDITOR -p "${manifest[@]}"
Run Code Online (Sandbox Code Playgroud)

  • +1 用于提供我怀疑是很少使用的命令动词 (4认同)
  • 啊。`( IFS=$'\n'; select file in $(find -maxdepth 2 -name '*.txt'); do echo "$file"; done; )` (3认同)