1

I have a directory, sub-directories each containing some text files.

 main-dir
  |
  sub-dir1
         | file1 "foo"
  |
  sub-dir2
         | file2 "bar"
  |
  sub-dir3
         | file3 "foo"

These files file1, file2 contain same text. I want to segregate these sub-directories based on content of files. I would like to group sub-dir1 and sub-dir3 as files in these sub-dirs have same content. In this example, move sub-dir1 and sub-dir3 to another directory.

using grep in recursive mode lists out all subdirectories matching file content. How can I make use that of output.

4

2 回答 2

1

您的解决方案可以简化为:

for dir in *; do
  if grep "foo" "$dir/file1" >/dev/null; then
    cp -rf "$dir" "$HOME_PATH/newdir/"
  fi
done

但仅当所有目录都实际包含一个文件时才有效file1

像这样的东西:

grep -rl "foo" * | sed -r 's|(.*)/.*|\1|' | sort -u | while read dir; do
  cp -rf "$dir" "$HOME_PATH/newdir/"
done

或像这样:

grep -rl "foo" * | while read f; do
  dirname "$f"
done | sort -u | while read dir; do
  cp -rf "$dir" "$HOME_PATH/newdir/"
done

或像这样:

find . -type f -exec grep -l "foo" {} \; | xargs -I {} dirname {} | sort -u |
  while read dir; do
    cp -rf "$dir" "$HOME_PATH/newdir/"
  done

可能会更好。

于 2013-07-12T17:50:53.837 回答
0

我设法编写了这个脚本来解决我的问题。

PWD=`$pwd`
FILES=$PWD/*

for f in $FILES
do
    str=$(cat $f/file1)
    if [ "$str" == "foo" ];
    then
         cp -rf $f $HOME_PATH/newdir/
    fi

done
于 2013-07-12T14:52:22.683 回答