如何对grep在tar归档文件的模式,而不会填满磁盘空间 [英] How to grep for a pattern in the files in tar archive without filling up disk space
问题描述
我有一个tar归档,这是非常大〜5GB。
I have a tar archive which is very big ~ 5GB.
我想对grep上的所有文件的模式(也印有图案的文件的名称)存档,但不希望通过提取档案,填补了我的磁盘空间。
I want to grep for a pattern on all files (and also print the name of the file that has the pattern ) in the archive but do not want to fill up my disk space by extracting the archive.
反正我能做到这一点?
我尝试了这些,但是这并没有给我包含模式的文件名,只是匹配的行:
I tried these, but this does not give me the file names that contain the pattern, just the matching lines:
tar -O -xf test.tar.gz | grep 'this'
tar -xf test.tar.gz --to-command='grep awesome'
另外其中焦油此功能记录?焦油XF test.tar $文件
Also where is this feature of tar documented? tar xf test.tar $FILE
推荐答案
下面是我拿到这个:
while read filename; do tar -xOf file.tar "$filename" | grep 'pattern' | sed "s|^|$filename:|"; done < <(tar -tf file.tar | grep -v '/$')
爆发了解释:
-
同时读取的文件名;做
- 这是一个循环...... -
焦油-xOf文件.tar$文件名
- 此提取每个文件... -
| grep的'模式'
- 这里就是你把你的模式... -
| SEDS | ^ | $文件名:|
- prePEND文件名,所以这个样子的grep。盐适量。 -
完成&LT; ≤(焦油-tf文件.tar | grep的-v'/ $')
- 结束循环,获取文件的列表,以FEAD你的而读
。
while read filename; do
-- it's a loop...tar -xOf file.tar "$filename"
-- this extracts each file...| grep 'pattern'
-- here's where you put your pattern...| sed "s|^|$filename:|";
- prepend the filename, so this looks like grep. Salt to taste.done < <(tar -tf file.tar | grep -v '/$')
-- end the loop, get the list of files as to fead to yourwhile read
.
一个条件:这打破,如果你有或棒材( |
),在您的文件名
One proviso: this breaks if you have OR bars (|
) in your filenames.
嗯。其实,这使得一个不错的bash函数,你可以附加到你的的.bashrc
文件:
Hmm. In fact, this makes a nice little bash function, which you can append to your .bashrc
file:
targrep() {
local taropt=""
if [[ ! -f "$2" ]]; then
echo "Usage: targrep pattern file ..."
fi
while [[ -n "$2" ]]; do
if [[ ! -f "$2" ]]; then
echo "targrep: $2: No such file" >&2
fi
case "$2" in
*.tar.gz) taropt="-z" ;;
*) taropt="" ;;
esac
while read filename; do
tar $taropt -xOf "$2" \
| grep "$1" \
| sed "s|^|$filename:|";
done < <(tar $taropt -tf $2 | grep -v '/$')
shift
done
}
这篇关于如何对grep在tar归档文件的模式,而不会填满磁盘空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!