[英]Replace specific rows with values from another text file in shell scripting?
I have a file that is 8 rows of single asterixes. 我有一个文件,它是8行的单星号。 I have 4 text files, with two rows of numbers in each.
我有4个文本文件,每个文件有两行数字。 I want to create a new file for each of the text files, where row number i+2 and i+3 is replaced by the content of the text file.
我想为每个文本文件创建一个新文件,其中行号i + 2和i + 3被文本文件的内容替换。 For example:
例如:
File1 would be: File1将是:
1 5 7 8
2 4 5 6
I want to convert it to: 我想将其转换为:
1 5 7 8
2 4 5 6
*
*
*
*
*
*
And File2 would converted from: File2将转换为:
6 5 6 7
8 9 0 9
to: 至:
*
*
6 5 6 7
8 9 0 9
*
*
*
*
Is there a way to iterate through text files in a directory, converting each text file like above? 有没有办法遍历目录中的文本文件,像上面那样转换每个文本文件?
Thanks! 谢谢!
UPDATE: Maybe this will explain it better: 更新:也许这会更好地解释它:
Basically I have n-number of text files, each having only two rows of numbers. 基本上我有n个文本文件,每个文本文件只有两行数字。 I want to cycle through the text files, converting each text file into another text file where there is nx 2 number of rows, with the first text file's values taking up row 1 & 2 and the rest of the rows are *.
我想循环浏览文本文件,将每个文本文件转换为另一个文本文件,其中行数为nx 2,第一个文本文件的值占行1和2,其余行为*。 The second text file would have nx 2 rows, but the 3rd and 4th row are the files values, with the rest being *.
第二个文本文件将具有nx 2行,但是第3和第4行是文件值,其余为*。 The third file having nx 2 rows, with the 6 & 7th row being populated with its values and rest being *, and so on.
第三个文件具有nx 2行,第6和第7行使用其值填充,其余为*,依此类推。
Not sure how to do this easily in shell, but GNU awk has some features that make it pretty straightforward. 不知道如何在shell中轻松地做到这一点,但是GNU awk具有一些使其非常简单的功能。
parse.awk parse.awk
BEGINFILE {
outfile = ARGV[ARGIND] ".new"
for(i=1; i<ARGIND; i++)
print "*\n*" > outfile
}
{ print > outfile }
ENDFILE {
for(i=1; i<ARGC-ARGIND; i++)
print "*\n*" > outfile
close(outfile)
}
Run it like this: 像这样运行它:
gawk -f parse.awk File*
ARGV is an array and holds the names of the input files. ARGV是一个数组,其中包含输入文件的名称。 ARGIND is the index into ARGV to the file currently being processed, ARGC is the length of ARGV, ie the number of arguments given.
ARGIND是ARGV到当前正在处理的文件的索引,ARGC是ARGV的长度,即给定的参数数。
The BEGINFILE and ENDFILE blocks are executed when beginning/finished the processing of a file, so they're convenient hooks in your case. BEGINFILE和ENDFILE块在开始/结束文件处理时执行,因此它们很方便。
bash
solution: bash
解决方案:
n=8
i=0
for file in * ; do
{
for ((a=0 ; a<n ; a++)) ; do
((a==i)) && cat "$file"
echo $'*\n*'
done
} > "$file".out
let i++
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.