将文件中的行 x 替换为另一个文件中的行 x

Replace line x from a file with line x from another file

我有如下两个文件:

file1:
a b c
1 2 3
a y z

file2:
A B C
0 0 0
A Y Z

我想根据模式将 file1 中的第 1 行替换为 file2 中的第 1 行,将 file1 中的第 3 行替换为 file2 中的第 3 行,或将任何其他行替换为其他文件中的等效行。 (这两个文件总是有相同的行数,我总是知道一个文件中的第 x 行将替换另一个文件中的第 x 行)。

我试过这个:

while read -r line; do
    if [[ $line == "A"* ]]; then
        VAR=$line
        while read -r line; do
            if [[ $line == "a"* ]];then
                sed -i "s/$line/$VAR/g" file1.txt
            fi
        done < file1.txt
    fi
done < file2.txt

输出为:

A B C
1 2 3
A B C

期望的输出应该是:

A B C
1 2 3
A Y Z

这不起作用,因为 VAR 在嵌套 while 循环结束之前不会更改。 有人可以为此提供更简单的解决方案吗?

谢谢!

假设替换条件是 file1 中的一行以 a 开头,正如您的尝试所暗示的那样:

awk 'NR == FNR { line[NR] = [=10=]; next } /^a/ { [=10=] = line[FNR] } 1' file2 file1

对于其他条件,只需将 /^a/ 替换为标识要替换的行的条件。

这是通过首先将 file2 的行读入数组并在条件成立时在处理 file1 时交换它们来实现的。详细:

NR == FNR {       # if the number of the current record is the same as the
                  # number of the current record in the current file -- that
                  # is: while processing the first file (file2)
  line[NR] = [=11=]   # remember the line by that number
  next            # do nothing else
}
                  # afterwards (while processing the second file (file1)):
/^a/ {            # if the current record begins with a
  [=11=] = line[FNR]  # swap in the corresponding remembered line
}
1                 # print

您需要更改正则表达式,使其匹配小写 "a"。您还需要在 if 语句中添加波浪线“~”以使其执行正则表达式。这需要为两个 if 语句完成 - try:

while read -r line; do
if [[ $line =~ ([aA]*) ]]; then
    VAR=$line
    while read -r line; do
        if [[ $line =~ ([aA]*) ]];then
            sed -i "s/$line/$VAR/g" file1.txt
        fi
    done < file1.txt
fi
done < file2.txt