简体   繁体   English

使用 bash 中的另一个文件替换 txt 文件中的多行

[英]replace multiple lines in a txt file using another file in bash

I have two files "file1.txt" and "file2.txt" containing the same number of lines.我有两个包含相同行数的文件“file1.txt”和“file2.txt”。 I want to replace the odd lines of file2.txt by the odd lines of file1.txt.我想用 file1.txt 的奇数行替换 file2.txt 的奇数行。

Example:例子:

file1.txt文件1.txt

header1.1
content1.1
header1.2
content1.2
header1.3
content1.3

file2.txt:文件2.txt:

content2.1
header2.2
content2.2
header2.3
content2.3

The result I want:我想要的结果:

file2.txt:文件2.txt:

header1.1
content2.1
header1.2
content2.2
header1.3
content2.3

Thank you in advance先感谢您

This will do it, assuming that header2.1 should be the first line of file2.txt .这将做到这一点,假设header2.1应该是file2.txt的第一行。

I=1
paste -d '\n' file1.txt file2.txt | while read line ; do 
  if [ `expr \( $I + 3 \) % 4` -eq 0 ] ; then echo "$line" ; fi 
  if [ `expr  $I % 4` -eq 0 ] ; then echo $line ; fi 
  I=`expr $I + 1`
done

I'm using the paste -d '\n' file1.txt file2.txt to combine the 2 files into one stream with alternating lines that I then need to extract the correct row numbers.我正在使用paste -d '\n' file1.txt file2.txt将 2 个文件组合成一个 stream 交替行,然后我需要提取正确的行号。 If you note that result of the paste looks something like:如果您注意到粘贴的结果类似于:

[row 1] header1.1
[row 2] header2.1
[row 3] content1.1
[row 4] content2.1
[row 5] header1.2
[row 6] header2.2
[row 7] content1.2
[row 8] content2.2
....

It seems you want the odd lines of file1.txt and the even lines of file2.txt.看来您想要 file1.txt 的奇数行和 file2.txt 的偶数行。 In the combined example, you want row 1 and row 4 for each set of 4 rows.在组合示例中,您需要每组 4 行的第 1 行和第 4 行。

This takes the line number, adds 3 and checks if that's divisible by 4 with no remainder by using the % (modulus) operator.这需要行号,添加 3 并使用 % (模数)运算符检查它是否可以被 4 整除且没有余数。 This will match for row 1, row 5, row 9, etc.这将匹配第 1 行、第 5 行、第 9 行等。

expr \( $I + 3 \) % 4

This checks that the line number is divisible by 4这将检查行号是否可以被 4 整除

expr  $I % 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM