shell每n行插入一行 [英] shell insert a line every n lines

查看:595
本文介绍了shell每n行插入一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件,我试图从file2插入一行到file1,每隔4行从file1开始。例如:

file1:

 第1行
线2
线3
线4
线5
线6
线7
线8
线9
线10

file2:

  50 
43
21

得到:

  50 
线1
线2
线3
第4行
43
行5
行6
行7
行8
21
行9
行10

我有这个代码:

  while read line 
do
sed'0〜4 s / $ / $ line / g'< file1.txt> file2.txt
完成< file1.txt

我得到以下错误:

  sed:1:0〜4 s / $ / $ line / g:无效的命令代码〜
$ b

解决方案

下面的步骤通过这两个文件,不加载任何一个到内存中的数组:

  awk'(NR-1)%4 == 0 {getline this   

如果您的实际 file2 大于您想要保存的内存。

这个分解如下:


  • (NR-1)%4 == 0 - 匹配从第4行开始的每一行的条件
  • getline this<file2 - 从file2中获取一行并将其存储在变量 this

  • 打印这个 - 打印...这个。

  • 1 当前行,在这种情况下来自file1(awk正常的输入)


I have two files and I am trying to insert a line from file2 into file1 every other 4 lines starting at the beginning of file1. So for example:

file1:

line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10

file2:

50
43
21

output I am trying to get:

50
line 1
line 2
line 3
line 4
43
line 5
line 6
line 7
line 8
21
line 9
line 10

The code I have:

while read line
do
    sed '0~4 s/$/$line/g' < file1.txt > file2.txt
done < file1.txt

I am getting the following error:

sed: 1: "0~4 s/$/$line/g": invalid command code ~

解决方案

The following steps through both files without loading either one into an array in memory:

awk '(NR-1)%4==0{getline this<"file2";print this} 1' file1

This might be preferable if your actual file2 is larger than what you want to hold in memory.

This breaks down as follows:

  • (NR-1)%4==0 - a condition which matches every 4th line starting at 0
  • getline this<"file2" - gets a line from "file2" and stores it in the variable this
  • print this - prints ... this.
  • 1 - shorthand for "print the current line", which in this case comes from file1 (awk's normal input)

这篇关于shell每n行插入一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆