[英]How to loop over files and save output in different files using sed?
I have two different files A.txt and B.txt both containing the same string. 我有两个不同的文件A.txt和B.txt都包含相同的字符串。 I would like to use a
sed
command in order to replace the strings but I do not want to overwrite A.txt and B.txt. 我想使用
sed
命令来替换字符串,但我不想覆盖A.txt和B.txt。
Actually I would like to loop over files and then do something like this for both : 实际上,我想遍历文件,然后对两个文件都执行以下操作:
sed 's/myString/myNewString/g' A.txt > updatedA.txt
What trick can I use in order to redirect outputs this way for as many files as I want ? 为了以这种方式将输出重定向到任意数量的文件,我可以使用什么技巧? Let's assume I've got x *.txt files.
假设我有x * .txt文件。
Thanks. 谢谢。
With a for
loop for all .txt files in current directory: 对于当前目录中的所有.txt文件,使用
for
循环:
for file in *.txt; do
sed 's/myString/myNewString/g' "$file" > "updated$file"
done
Use this script only once per directory. 每个目录只能使用一次此脚本。
This might work for you (GNU parallel): 这可能对您有用(GNU并行):
parallel sed 's/myString/myNewString/g' {} \> updated{} ::: *.txt
This will loop through all txt files in the current directory and make amendments/copies to new files prefixed by updated
. 通过所有txt文件这将循环在当前目录下,并做出修正/份由前缀的新文件
updated
。
If you only want create files for those with changes, use: 如果只想为有更改的文件创建文件,请使用:
parallel grep myString {} \&\& sed 's/myString/myNewString/g' {} \> updated{} ::: *.txt
Or re-curse through all txt
files in a directory, use: 或重新遍历目录中的所有
txt
文件,请使用:
find . -name '*.txt' | parallel sed 's/myString/myNewString/g' {} \> {//}/updated{/}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.