gpt4 book ai didi

linux - "find -exec sh -c"内的 grep 变量扩展

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:50:20 26 4
gpt4 key购买 nike

我编写了一个脚本,循环遍历 word 文档以匹配其中的单词。下面是一个有效的示例,它找到了数字 43。接下来是一个不起作用的脚本。我只想将数字 43 作为脚本开头的变量,但它似乎无法正确扩展。有什么想法可以让我的脚本中有 43 作为变量而不是硬编码吗?

有效的脚本:

find . -type f -name '*.docx' -exec sh -c '
for file do
docx2txt "$file" 2>/dev/null - | grep -i --color "43" && printf "\033[1;32mFound in ${file}\033[0m\n"
#readlink -f "$file"
done
' sh {} +

不起作用的脚本:

scan_var=43
find . -type f -name '*.docx' -exec sh -c '
for file do
docx2txt "$file" 2>/dev/null - | grep -i --color "$scan_var" && printf "\033[1;32mFound in ${file}\033[0m\n"
#readlink -f "$file"
done
' sh {} +

最佳答案

从安全角度来看,您应该使用 export 通过环境将变量公开给子进程,而不是将这些变量替换为解析为代码的字符串(这有助于 shell injection 攻击)。

即:

export scan_var=43  ## the **only** change is to this line!

# only modifications to code below are formatting with no functional impact
# ...well, and safer printf use (to not expand format strings in filenames)
find . -type f -name '*.docx' -exec sh -c '
for file do
docx2txt "$file" 2>/dev/null - \
| grep -i --color "$scan_var" \
&& printf "\033[1;32mFound in %s\033[0m\n" "$file"
done
' sh {} +

关于linux - "find -exec sh -c"内的 grep 变量扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55046798/

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