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

时间:2015-03-20 15:45:59

标签: bash shell awk sed

我有两个文件如下:

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

DESIRED输出应为:

A B C
1 2 3
A Y Z

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

谢谢!

2 个答案:

答案 0 :(得分:1)

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

awk 'NR == FNR { line[NR] = $0; next } /^a/ { $0 = 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] = $0   # 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
  $0 = line[FNR]  # swap in the corresponding remembered line
}
1                 # print

答案 1 :(得分:0)

您需要更改正则表达式,以便它与小写字母匹配&#34; a&#34;。你还需要添加tilda&#34;〜&#34;在if语句中让它做一个正则表达式。这两个if语句都需要这样做 - 尝试:

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
相关问题