我尝试用 替换文本文件中的某些文本,sed
但不知道如何对多个文件进行替换。
我使用:
sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g /path/to/file/target_text_file
在处理多个文件之前,我使用以下命令在文本文件中打印了目标文本文件的路径:
find /path/to/files/ -name "target_text_file" > /home/user/Desktop/target_files_list.txt
现在我想sed
按照 来运行target_files_list.txt
。
答案1
您可以使用循环来循环遍历文件while ... do
:
$ while read i; do printf "Current line: %s\n" "$i"; done < target_files_list.txt
对于您来说,您应该printf ...
用sed
您想要的命令进行替换。
$ while read i; do sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g' "$i"; done < target_files_list.txt
但是,请注意,您只需使用以下命令即可实现您想要的目标find
:
$ find /path/to/files/ -name "target_text_file" -exec sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g' {} \;
您可以-exec
通过运行以下命令了解有关选项的更多信息man find | less '+/-exec '
:
-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.
编辑:
正如用户正确指出的那样
特登和甜点在注释中,必须使用-r
with,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.
所以应该是:
$ while read -r i; do sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g' "$i"; done < target_files_list.txt
答案2
一种方法是使用xargs
:
xargs -a target_files_list.txt -d '\n' sed -i -- 's/SOME_TEXT/TEXT_TO_REPLACE/g'
从man xargs
:
-a file, --arg-file=file
Read items from file instead of standard input.
--delimiter=delim, -d delim
Input items are terminated by the specified character. The
specified delimiter may be a single character, a C-style charac‐
ter escape such as \n, or an octal or hexadecimal escape code.
答案3
只需使用for
循环。
IFS=$'\n' # Very important! Splits files on newline instead of space.
for file in $(cat files.txt); do
sed ...
done
请注意,如果您遇到名称中带有换行符(!)的文件,您将会遇到问题。(: