Why `read line; declare $line` and `find … +`?

2019-08-15 12:10发布

The below script works, but what purpose does the declare $line have? If I remove it, it doesn't work.

And what is the difference of {} \; and {} + in the find command?

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

标签: linux bash
2条回答
啃猪蹄的小仙女
2楼-- · 2019-08-15 12:20

The declare or typeset Builtins, which are exact synonyms, permit modifying the properties of variables. This is a very weak form of the typing available in certain programming languages. The declare command is specific to version 2 or later of Bash. The typeset command also works in Ksh scripts.

查看更多
等我变得足够好
3楼-- · 2019-08-15 12:24

The declare is setting variables: Your awk command emits contents of the form old=foo new=bar. Running declare old=foo new=bar sets those two variables.

That said, this is a wrong and sloppy way to do this. Instead, use read to directly read the desired fields from the input file and assign to the variables (more on this in 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

To make this a bit safer, one can also escape literal content against being treated as regular expressions:

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

Note that I haven't changed the use of \b, an extension which many implementations of sed won't support. See BashFAQ #21 for alternative approaches to doing literal string substitutions.


For completeness (though this unrelated topic really should have been asked as a separate question -- and could have, in that case, been closed as duplicate, as it's been asked and answered before), allow a quotation from the find man page:

  -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.
查看更多
登录 后发表回答