在多个文件中用另一行替换一行

在多个文件中用另一行替换一行

我必须将一个文件中的行内容替换为多个文件中的另一行(在同一位置编号 3 中)。问题如下所示:

输入1

file.list <- list("a","b","c","d")
file.list <- list("d","e","f","g")
file.list <- list("h","i","l","m")

输入2.文件

library(data.table)
library(dplyr)
file.list <- list("z","g","h","s","i")

输入3.文件

library(data.table)
library(dplyr)
file.list <- list("s","p","q","r","m")

输入4.文件

library(data.table)
library(dplyr)
file.list <- list("x","k","s","e")

Input2.file 的输出

library(data.table)
library(dplyr)
file.list <- list("a","b","c","d")

Input3.file 的输出

library(data.table)
library(dplyr)
file.list <- list("d","e","f","g")

Input4.file 的输出

library(data.table)
library(dplyr)
file.list <- list("h","i","l","m")

我尝试执行以下操作:

filename='Input1'
for i in *.file; do #here i loop over the list of files
    while read p $filename; do #here i loop over the lines of Input1 file
        awk '{ if (NR == 3) print "$p"; else print $0}' $i > $i.test; ##here i substitute the line 1 in the files with the line that are in Input1 file
    done;
done

我做错了什么,因为脚本在没有给我任何消息的情况下停止了。我做错了什么?任何想法?

答案1

$ gawk -i inplace '
    NR == FNR {repl[FNR] = $0; next} 
    FNR == 1  {filenum++} 
    FNR == 3  {$0 = repl[filenum]} 
    {print}
' Input1 Input{2,3,4}.file

$ cat Input2.file
library(data.table)
library(dplyr)
file.list <- list("a","b","c","d")

$ cat Input3.file
library(data.table)
library(dplyr)
file.list <- list("d","e","f","g")

$ cat Input4.file
library(data.table)
library(dplyr)
file.list <- list("h","i","l","m")

查看您的代码:

  1. 您将每个 *.file 中的第 3 行替换为 Input1 的每一行。对于每个 *.file,您将看到 Input1 的最后一行作为第 3 行。
  2. $p无法在 awk 脚本中展开,因为它用单引号引起来。

尝试这个:

exec 3<Input1   # set up file descriptor 3 to read from Input1 file
for f in *.file; do
    read -r -u 3 replacement   # read a line from fd 3  
    awk -v rep="$replacement" '{if (NR == 3) print rep; else print $0}' "$f" > "$f.test"
done
exec 3<&-       # close fd 3

答案2

用另一行替换文件中的行内容

bash+sed解决方案:

i=0; for f in Input[2-4].file; do ((i++)); sed -n "${i}p" "Input1" > "$f"; done

查看结果:

$ head Input[2-4].file
==> Input2.file <==
file.list <- list("a","b","c","d")

==> Input3.file <==
file.list <- list("d","e","f","g")

==> Input4.file <==
file.list <- list("h","i","l","m")

相关内容