且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

列出目录1中但不在目录2中的文件,反之亦然?

更新时间:2023-11-29 18:54:16

有点粗糙-但我一直使用的最简单方法是(可以使用diff params,我通常使用不同的grep

a bit crude - but the easiest way I always use is (can play with the diff params, I typically use different grep

diff -rcw DIR1 DIR2| grep ^Only

然后您可以根据需要进行排序和格式化

then you can sort and format as you like

修改为格式(效率较低,因为我们在这里两次运行diff ...很容易解决)

Revised to format (less efficient as we are running diff twice here ... easily solved)

echo files only in $dir1
LST=$(diff ${dir1} ${dir2}| grep "^Only in ${dir1}"| sed 's@^.*: @@')
(cd ${dir1}; ls -l ${LST})

echo files only in $dir2
LST=$(diff ${dir1} ${dir2}| grep "^Only in ${dir2}"| sed 's@^.*: @@')
(cd ${dir2}; ls -l ${LST})

扩展上面的sed表达式:
s =搜索并替换
三个'@'分隔表达式(这通常是用'/'完成的)
^匹配行的开头(强制其余部分不匹配) .表示任何字符
*表示前一个表达式(.==与任何字符匹配)0-N次 :"是我从差异输出仅在X:"

Expanding on the sed expression above:
s=search and replace
the three '@' are separating the expressions (this is TRADITIONALLY done with '/')
^ matches the beginning of a line (forces the rest not to match elsewhere) . means any character
* means the previous expression (.==match any char) 0-N times ": " is what I matched on from the diff output "Only in X: "

看妈咪,别动手-现在没有"sed",它的开始就越来越粗糙了

Look Mommy, no hands - now without 'sed' its beginning to be less and less crude

XIFS="${IFS}"
IFS=$'\n\r'
for DIFFLINE in $(diff ${dir1} ${dir2}|grep ^Only); do
  case "${DIFFLINE}" in
   "Only in ${dir1}"*)  
    LST1="${LST1} ${DIFFLINE#*:}"
    ;;
   "Only in ${dir2}"*)  
    LST2+="${DIFFLINE#*:}"
    ;;
  esac
done
IFS="${XIFS}"

echo files only in $dir1
(cd ${dir1}; ls -l ${LST1})

echo files only in $dir2
(cd ${dir2}; ls -l ${LST2})

您可能想了解IFS ...它需要在bash手册中进行一些阅读,但基本上是字段分隔符...默认情况下,它们包含空格,并且我不希望循环被填充行的分数,只是完整的行-因此,在循环期间,我将默认的IFS覆盖为换行符和回车符.

You will probably want to know about IFS ... it needs some reading in the bash manual, but its basically the field separator characters ... by default they include spaces and I don't want the loop to be fed with fractions of lines, just complete lines - so for the duration of the loop I override the default IFS to just newlines and carriage returns.

顺便说一句,也许您的教授正在阅读***,也许接下来您将不被允许使用分号;-) ...(回到'man bash'... BTW,如果您在emacs中使用'man bash'做,更加容易阅读IMO)

BTW maybe your professor is reading ***, maybe next you wont be allowed to use semicolons ;-) ... (back to 'man bash' ... BTW if you do 'man bash' do it in emacs, makes much easier to read IMO)