使用awk将特定行号从一个文件复制到另一个文件的特定行号

时间:2022-12-09 16:03:52

I have a .txt file with 71 lines and I have another 12 set of files(file1 to file12). I want to copy first 5 lines from .txt file to file1 on specific line numbers similarly next 5 lines from .txt to file2 again on specific line numbers and so on.

我有一个71行的.txt文件,我有另外12组文件(file1到file12)。我想将.txt文件中的前5行复制到特定行号上的file1,然后再将特定行号从.txt复制到file2,依此类推。

This is my current code:

这是我目前的代码:

n = 1
sed -i '52,56d' $dumpfile 
awk'{print $'"$n"',$'"$n+1"',$'"$n+2"',$'"$n+3"'}' sample.txt > $dumpfile
n=$(($n + 1))

In $dumpfile I have put my 12 files.

在$ dumpfile中我放了12个文件。

Sample file (12files; file1, file2...)

示例文件(12files; file1,file2 ......)

...........  
................  
..............  
abc = 4,1,3  
def = 1,2,6  
dfg = 28,36,4  
tyu = 68,47,6  
rty = 65,6,97 

file (sample.txt)

abc = 1,2,3  
def = 4,5,6  
dfg = 2,3,4  
tyu = 8,7,6  
rty = 5,6,7

abc = 21,2,32  
def = 64,53,6  
dfg = 28,3,4  
tyu = 18,75,6  
rty = 5,63,75

...........  
...........  

I want to replace these five lines of (file1... file12) with five lines of sample.txt file. Line number of lines to be replaced in file1 to file12 are same in all the 12 files, where as in sample.txt file first set of 5 lines will go in file1, second set of 5 lines will go in file2 and so on upto file12.

我想用五行sample.txt文件替换这五行(file1 ... file12)。在file1到file12中要替换的行数在所有12个文件中是相同的,其中在sample.txt文件中,第一组5行将进入file1,第二组5行将进入file2,依此类推至file12 。

1 个解决方案

#1


What you need is something like, this (uses GNU awk for ARGIND and inplace editing):

你需要的是这样的东西(使用GNU awk进行ARGIND和现场编辑):

awk -i inplace -v start=52 '
NR==FNR {new[NR]=$0; next}
FNR==start {print new[ARGIND-1]; c=5}
!(c&&c--)
' RS="" sample.txt RS='\n' file1 file2 ... file12

but until you post some testable sample input and the associated output it's just a guess and, obviously, untested.

但是在你发布一些可测试的样本输入和相关的输出之前,它只是一个猜测,显然是未经测试的。

#1


What you need is something like, this (uses GNU awk for ARGIND and inplace editing):

你需要的是这样的东西(使用GNU awk进行ARGIND和现场编辑):

awk -i inplace -v start=52 '
NR==FNR {new[NR]=$0; next}
FNR==start {print new[ARGIND-1]; c=5}
!(c&&c--)
' RS="" sample.txt RS='\n' file1 file2 ... file12

but until you post some testable sample input and the associated output it's just a guess and, obviously, untested.

但是在你发布一些可测试的样本输入和相关的输出之前,它只是一个猜测,显然是未经测试的。