gpt4 book ai didi

perl - 如何使用 unix 列出在文件夹中找不到的字符串

转载 作者:行者123 更新时间:2023-12-02 03:18:08 25 4
gpt4 key购买 nike

我在文本文件中有一个字符串列表。源文件夹有一些包含字符串的文件。如果在源文件夹中找到字符串,我会将其复制到目标文件夹。

srcdirectory - 用于检查字符串是否存在的源目录。
stringList.txt - 要测试的字符串列表。
目标 - 将找到的字符串复制到此文件夹。

例如,
srcdirectory 有文件:

a.edi (contains string 'a' in the content of the file)                                                                                      
b.edi (contains string 'b' in the content of the file)
c.edi (contains string 'c' in the content of the file)
d.edi (contains string 'd' in the content of the file)
e.edi (contains string 'e' in the content of the file)
f.edi (contains string 'f' in the content of the file)
g.edi (contains string 'g' in the content of the file

stringList.txt 有字符串:

a              
b
c
d
e
f
g

如果找到字符串的匹配项,它将匹配的文件名复制到目标文件夹。所以 target 文件夹包含匹配的文件名:

 a.edi            
c.edi
g.edi

现在,我希望将不匹配的字符串列表复制到与下面不同的文件夹中。我该怎么做?

    b
d
e
f

这是我的匹配字符串脚本:

find srcdirectory/ -maxdepth 2 -type f -exec grep -Ril -f stringList.txt {} \; -exec cp -i {} /home/Rose/target \;

任何帮助将不胜感激..

最佳答案

一般来说,您可以在 find 中使用 -o 运算符进行逆运算:

find srcdirectory -maxdepth 2 -type f \( \
-exec grep -qif stringList.txt {} \; -exec cp -i {} /home/Rani/target \; \
\) -o -exec cp -i {} /home/Rani/nonmatches \;

这里的技巧是,对于匹配的文件,括号内的表达式必须为“true”(成功/0 退出状态),否则为 false。如果 cp -i 无法匹配文件,这将是不精确的。如果您担心这种可能性,则需要捕获 grep -q 的状态并在 cp 表达式之后重新应用它。

也许使用 bash 会更容易。

find srcdirectory -maxdepth 2 -type f -exec bash -c '
for file; do
if grep -qif stringList.txt "$file"; then
cp -i "$file" /home/Rani/target
else
cp -i "$file" /home/Rani/nonmatches
fi
done
' _ {} +

关于perl - 如何使用 unix 列出在文件夹中找不到的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35344274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com