Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 在Unix中将文件中的行从行号'n1'移动到行号'n2'_Bash_File_Shell_Unix_Sed - Fatal编程技术网

Bash 在Unix中将文件中的行从行号'n1'移动到行号'n2'

Bash 在Unix中将文件中的行从行号'n1'移动到行号'n2',bash,file,shell,unix,sed,Bash,File,Shell,Unix,Sed,我有一个名为file1的文件,如下所示 1 intst 2 1.0 3 12.591870 0.000000 0.000000 4 0.000000 12.591870 0.000000 5 0.000000 0.000000 12.591870 6 Ba Zr Al O 7 27 26 1 81 8 direct 9 0.166667 0.166666 0.167762 Ba 10 0.166667 0.166667 0.500000 Ba #Line

我有一个名为
file1
的文件,如下所示

  1 intst
  2 1.0
  3 12.591870 0.000000 0.000000
  4 0.000000 12.591870 0.000000
  5 0.000000 0.000000 12.591870
  6 Ba Zr Al O
  7 27 26 1 81
  8 direct
  9 0.166667 0.166666 0.167762 Ba
 10 0.166667 0.166667 0.500000 Ba  #Line to be moved
 11 0.166666 0.166667 0.832238 Ba
 ...
 ...
 60 0.666668 0.666666 0.329117 Zr
 61 0.666665 0.666667 0.670884 Zr
 62 0.666667 0.666667 1.000000 Al #Moved line to be inserted below this line
 63 0.166667 0.999071 0.999999 O
我需要复制
line-10
的内容,并通过创建新行将其移动到
line-62
下方,以便新文件内容显示为

  1 intst
  2 1.0
  3 12.591870 0.000000 0.000000
  4 0.000000 12.591870 0.000000
  5 0.000000 0.000000 12.591870
  6 Ba Zr Al O
  7 27 26 1 81
  8 direct
  9 0.166667 0.166666 0.167762 Ba
 10 0.166666 0.166667 0.832238 Ba #Original line- 11
 ...
 ...
 59 0.666668 0.666666 0.329117 Zr
 60 0.666665 0.666667 0.670884 Zr
 61 0.666667 0.666667 1.000000 Al
 62 0.166667 0.166667 0.500000 Ba #Original line-10
 63 0.166667 0.999071 0.999999 O
使用sed我知道如何删除一行

sed -i.bkp -e '10d' file
和插入一行

sed -i '10i <string>'file1
sed-i'10i'文件1

但我不知道如何复制一行内容并将其移动到另一行

您可以使用此
sed

sed '10{h;D}; 62G' file
根据@Benjamin的评论,您也可以使用
d

sed '10{h;d}; 62G' file
使用
-i.bak
进行就地编辑

这里,

  • 10和62
    -行号
  • h
    -复制图案空间以保留空间。这将保存
    第10行
    以保留空间
  • G
    -将保留空间附加到图案空间。这将
    第10行
    追加到模式空间
  • D
    -删除模式空间中直到第一个换行符的文本
    • awk:

      awk -v n1=10 -v n2=62 '
          NR == n1 {line=$0; next}
          {print}
          NR == n2 {print line}
      ' file > file.new
      
      或受尊敬的人(就地编辑文件)


      ed文件您能解释一下选项h、D和G是如何工作的吗?我删除了与您的答案太相似的答案,但为什么不干脆
      sed'10h;62G'文件
      因为OP想要复制行,而不是移动它?@Kenavoz,
      h
      不会从模式空间删除文本。@BenjaminW.,更新了答案。@WanderingMind,试试这个:
      sed-e'10{h;d};'-e'62G'文件
      @潜行者示例建议使用“移动”。如果对您很重要,ed命令可以以各种方式“一行”执行。