![](/img/trans.png)
[英]cd && ls | grep: How to execute a command in the current shell and pass the output
[英]How to cd into grep output?
我有一個Shell腳本,它基本上會搜索某個位置內的所有文件夾,並且我使用grep來查找要定位的確切文件夾。
for dir in /root/*; do
grep "Apples" "${dir}"/*.* || continue
盡管grep成功找到了目標目錄,但我仍在如何移動要移動到目標目錄中的文件夾。 我當時的想法是cd到grep輸出,但這就是我遇到的問題。 嘗試了一些Google結果,但對我的案子沒有任何幫助。
grep輸出示例:二進制文件/root/ant/containers/secret/Documents/2FD412E0/file.extension matches
我想光盤進入2FD412E0
並在該目錄中移動兩個文件夾。
dirname是實現此目的的關鍵:
cd $(dirname $(grep "...." ...))
將允許您輸入目錄。
就像人們提到的那樣, dirname
是從路徑中刪除文件名的正確工具。
我將使用find
執行此類任務:
while read -r file
do
target_dir=`dirname $file`
# do something with "$target_dir"
done < <(find /root/ -type f \
-exec grep "Apples" --files-with-matches {} \;)
考慮使用find
的-maxdepth
選項。 有關find
請參見手冊頁。
好吧,實際上有一個更簡單的解決方案:)我只想編寫bash腳本。 您可能只是使用單個find
命令,如下所示:
find /root/ -type f -exec grep Apples {} ';' -exec ls -l {} ';'
注意第二個-exec
。 如果先前的-exec
命令以狀態0
(成功)退出,它將被執行。 從手冊頁:
-exec command ;
執行命令; 如果返回0狀態,則為true。 后面的所有要查找的參數都將用作命令的參數,直到參數由;
組成;
遇到。 字符串{}
會被當前文件名替換,該文件名會在命令參數中出現的所有位置處進行處理,而不僅僅是在單獨的參數中(例如在某些版本的find中)。
用您的東西替換ls -l
命令。
如果要在-exec
命令中執行dirname
,則可以執行以下技巧:
find /root/ -type f -exec grep -q Apples {} ';' \
-exec sh -c 'cd `dirname $0`; pwd' {} ';'
用您的東西替換pwd
。
什么時候find
在您寫的注釋中, find
在您的系統上不可用。 以下解決方案無法find
:
grep -R --files-with-matches Apples "${dir}" | while read -r file
do
target_dir=`dirname $file`
# do something with "$target_dir"
echo $target_dir
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.