重复行范围 n 次

Repeat line range n times

我想多次重复 0.txt 文件中的所有行(从第 1 行到第 13 行)并在 [=61 中打印输出=]1.txt 文件.

0.txt:

{
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "file = open('out1.txt', 'a')\n",
    "sys.stdout = file\n",
    "print(foo.bar_bar((x,y), (x1,y1)))\n",
    "file.close()"
   ]
  },

唯一相关的(但还不够)command_01command_02 我知道的是

command_01:

awk '{while(++i<n)print;i=0}' 0.txt > 1.txt 

(其中 n > 1)

command_02:

sed -n '1,13p' source.txt > target.txt

我试图找到一些解决方案来调整 command_01 以便从 0.txt 文件的第 1 行到第 13 行获得几个重复的段, 但我暂时没有找到任何东西。

注意:我贴的是真实的文字,代表我的需要,所以根据上下文,我有必要运行解决0.txt[=73=的内容].

出于所有目的,考虑到我想重复 n 次(n > 1,总是)第 1 行和第 13 行之间的 0.txt 的所有行,我的 1.txt 输出文件应该是下面的内容:

1.txt:

    {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "file = open('out1.txt', 'a')\n",
    "sys.stdout = file\n",
    "print(foo.bar_bar((x,y), (x1,y1)))\n",
    "file.close()"
   ]
  },
      {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "file = open('out1.txt', 'a')\n",
    "sys.stdout = file\n",
    "print(foo.bar_bar((x,y), (x1,y1)))\n",
    "file.close()"
   ]
  },
      {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "file = open('out1.txt', 'a')\n",
    "sys.stdout = file\n",
    "print(foo.bar_bar((x,y), (x1,y1)))\n",
    "file.close()"
   ]
  },
    .
    .
    .
    .
    ... etc....

我希望我能有一个使用 AWK、SED、Perl 或某些正则表达式的解决方案,不一定按此顺序。如果您不能使用这些工具,那么我可以 运行 在 Bash.

关于选择的方案:

运行解决方案@JRFerguson,

perl -ne 'if (1..13) {push @data,$_};END{print @data for 1..3}' 0.txt > 1.txt,

到第 13 行被打印(至少对于我的测试)作为 },{

而不是

  },
  {

在这里查看我的完整输出 1.txt

但是使用此命令 awk '{gsub(/},{/,"},\n {");print}' 1.txt > 2.txt 我又添加了一个步骤,然后更正了与@JRFerguson 相关的第 13 行的输出。这样2.txt如下图:

{
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "file = open('out1.txt', 'a')\n",
    "sys.stdout = file\n",
    "print(subsystem.cause_info((1,2), (4,3)))\n",
    "file.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "file = open('out1.txt', 'a')\n",
    "sys.stdout = file\n",
    "print(subsystem.cause_info((1,2), (4,3)))\n",
    "file.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "file = open('out1.txt', 'a')\n",
    "sys.stdout = file\n",
    "print(subsystem.cause_info((1,2), (4,3)))\n",
    "file.close()"
   ]
  },

结合这个额外的命令,我认为@jrferguson 的回应已经足够了。

一种方法是:

perl -ne 'if (1..13) {push @data,$_};END{print @data for 1..3}' 0.txt > 1.txt

这会将 0.txt 文件的前 13 行读入数组。然后,数组的内容被写入3次(例如)到1.txt.

请注意 0.txt 文件只被读取一次。