如何找到在特定檔案中找到文本的目錄?例如,我想獲取“/var/www/”中包含檔案中文本“foo-bundle”的所有composer.json目錄。我有一個已經完成的命令:
find ./ -maxdepth 2 -type f -print | grep -i 'composer.json' | xargs grep -i '"foo-bundle"'
但是我想制作一個sh腳本來獲取所有這些目錄并用它們做事。任何的想法?
uj5u.com熱心網友回復:
找
您當前的命令幾乎就在那里,而不是使用xargswith grep,讓:
- 移動
grep到-exec - 使用
xargs打發結果dirname只顯示父檔案夾
find ./ -maxdepth 2 -type f -exec grep -l "foo-bundle" {} /dev/null \; | xargs dirname
如果您只想搜索composer.json檔案,我們可以包含如下-iname選項:
find ./ -maxdepth 2 -type f -iname '*composer.json' -exec grep -l "foo-bundle" {} /dev/null \; | xargs dirname
如果| xargs dirname沒有提供足夠的資料,我們可以擴展它,以便我們可以回圈find使用while read類似這樣的結果:
find ./ -maxdepth 2 -type f -iname '*composer.json' -exec grep -l "foo-bundle" {} /dev/null \; | while read -r line ; do
parent="$(dirname ${line%%:*})"
echo "$parent"
done
格雷普
我們可以用 格雷普 搜索包含特定文本的所有檔案。
之后的每一行上回圈,我們可以
- 洗掉后面的
:獲取檔案路徑 - 使用
dirname來獲取父檔案夾路徑
考慮這個檔案設定,/test/b/composer.json包含foo-bundle
? /tmp tree
.
├── test
│ ├── a
│ │ └── composer.json
│ └── b
│ └── composer.json
└── test.sh
運行以下命令時test.sh:
#!/bin/bash
grep -rw '/tmp/test' --include '*composer.json' -e 'foo-bundle' | while read -r line ; do
parent="$(dirname ${line%:*})"
echo "$parent"
done
結果如預期,檔案夾的路徑b:
/tmp/test/b
uj5u.com熱心網友回復:
為了查找包含特定文本的所有檔案,您可以使用:
find ./ -maxdepth 2 -type f -exec grep -l "composer.json" {} /dev/null \;
結果是檔案名串列。現在您需要做的就是找到一種dirname在所有這些上啟動命令的方法。(我嘗試使用一個簡單的管道,但這太容易了:-))
uj5u.com熱心網友回復:
感謝@0stone0 帶路。我終于得到了它:
#!/bin/sh
find /var/www -maxdepth 2 -type f -print | grep -i 'composer.json' | xargs grep -i 'foo-bundle' | while read -r line ; do
parent="$(dirname ${line%%:*})"
echo "$parent"
done
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/341855.html
上一篇:使用getitem運行Python程式時出現關鍵錯誤
下一篇:Python復制檔案到遠程
