首页 > 解决方案 > 替代在循环内使用 sed

问题描述

我想使用包含一行的文件替换大文件的多行(非连续)。我发现工作的是

for i in ${list[@]}; do
   line=$(cat file_$i.txt);
   sed -i "$i c $line" bigfile.txt;
done

在这里,list包含我要替换的行。这是一个例子:

$ list=(1 3 4 7)
$ cat file_1.txt
this is the new line 1
$ cat file_3.txt
this is the new line 3
$ cat file_4.txt
this is the new line 4
$ cat file_7.txt
this is the new line 7

$ cat bigfile.txt
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8

上述脚本的输出是

$ cat bigfile.txt 
newline 1
line 2
newline 3
newline 4
line 5
line 6
newline 7
line 8

它可以工作,但是据我了解,循环的每一步都会sed打开并读取整个文件,因此这种方法非常慢。还有什么其他更快的方法可以做到这一点,最好是使用sed

标签: sed

解决方案


一个可能的解决方案:

sed "$(for i in $list; do echo "$i c $(cat file_$i.txt)"; done)" bigfile.txt

$list可能必须是${list[@]}${list[*]}其他任何东西,取决于它的构造方式。)

您的原始循环用于构建一个 Sed 脚本,其中的每一行就像1 c content_of_file_1_dot_txt; 然后这个脚本只运行一次bigfile.txt


推荐阅读