ela*_*urk 5 bash find sed text-processing
我尝试将文本文件中的某些文本替换为 ,sed但不知道如何使用多个文件进行替换。
我用:
sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g /path/to/file/target_text_file
Run Code Online (Sandbox Code Playgroud)
在我使用多个文件之前,我使用以下命令在文本文件中打印了目标文本文件的路径:
find /path/to/files/ -name "target_text_file" > /home/user/Desktop/target_files_list.txt
Run Code Online (Sandbox Code Playgroud)
现在我想sed按照target_files_list.txt.
您可以使用循环遍历文件while ... do:
$ while read i; do printf "Current line: %s\n" "$i"; done < target_files_list.txt
Run Code Online (Sandbox Code Playgroud)
在你的情况下,你应该printf ...用sed你想要的命令替换。
$ while read i; do sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g' "$i"; done < target_files_list.txt
Run Code Online (Sandbox Code Playgroud)
但是,请注意,您可以仅使用以下内容来实现您想要的find:
$ find /path/to/files/ -name "target_text_file" -exec sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g' {} \;
Run Code Online (Sandbox Code Playgroud)
您可以-exec通过运行来阅读有关选项的更多信息man find | less '+/-exec ':
Run Code Online (Sandbox Code Playgroud)-exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.
由于正确地指出用户
terdon和甜品中有必要使用意见-r用read,因为它会正确处理反斜杠。它也被报道shellcheck:
$ cat << EOF >> do.sh
#!/usr/bin/env sh
while read i; do printf "$i\n"; done < target_files_list.txt
EOF
$ ~/.cabal/bin/shellcheck do.sh
In do.sh line 2:
while read i; do printf "\n"; done < target_files_list.txt
^-- SC2162: read without -r will mangle backslashes.
Run Code Online (Sandbox Code Playgroud)
所以应该是:
$ while read -r i; do sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g' "$i"; done < target_files_list.txt
Run Code Online (Sandbox Code Playgroud)