gpt4 book ai didi

linux - 为什么是 `read line; declare $line` 和 `find ... +` ?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:28:14 28 4
gpt4 key购买 nike

下面的脚本可以工作,但是 declare $line 的目的是什么?如果我删除它,它就不起作用。

find命令中的{}\;{} +有什么区别?

awk '{print "old="$1" new="$2}' list.txt |\
while IFS= read line; do
declare $line
find /path -name '*.ext' -exec sed -i "s/\b$old\b/$new/" {} +
done

最佳答案

declare 正在设置变量:您的 awk 命令发出 old=foo new=bar 形式的内容。运行 declare old=foo new=bar 设置这两个变量。

也就是说,这是一种错误且草率的方法。相反,使用 read 直接从输入文件中读取所需的字段并分配给变量(更多信息在 BashFAQ #1 中):

while read -u 3 -r old new _; do
find /path -name '*.ext' -exec sed -i "s/\b$old\b/$new/" {} +
done 3<list.txt

为了使这更安全一些,还可以转义文字内容以防止被视为正则表达式:

requote() { sed 's/[^^]/[&]/g; s/\^/\\^/g' <<< "$1"; };
substquote() { sed 's/[&/\]/\\&/g' <<< "$1"; }
while read -u 3 -r old new _; do
find /path -name '*.ext' -exec \
sed -i "s/\b$(requote "$old")\b/$(substquote "$new")/" {} +
done 3<list.txt

请注意,我没有更改 \b 的使用,这是 sed 的许多实现不支持的扩展。参见 BashFAQ #21用于进行文字字符串替换的替代方法。


为了完整起见(虽然这个不相关的话题真的应该作为一个单独的问题来问——并且在那种情况下,可以作为重复的问题关闭,因为它之前已经被问过和回答过),允许引用 查找手册页:

  -exec command {} +
This variant of the -exec action runs the specified command on
the selected files, but the command line is built by appending
each selected file name at the end; the total number of invoca‐
tions of the command will be much less than the number of
matched files. The command line is built in much the same way
that xargs builds its command lines. Only one instance of `{}'
is allowed within the command. The command is executed in the
starting directory.

关于linux - 为什么是 `read line; declare $line` 和 `find ... +` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28782665/

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