移动行以跟随文件中的另一行

Tod*_*ly' 5 linux awk

我有一个文件在文件中有一行如下:

check=('78905905f5a4ed82160c327f3fd34cba')
Run Code Online (Sandbox Code Playgroud)

我希望能够移动此行以遵循如下所示的行:

files=('somefile.txt')
Run Code Online (Sandbox Code Playgroud)

该阵列虽然有时可以跨越多行,例如:

files=('somefile.txt'
       'file2.png'
       'another.txt'
       'andanother...')

text
in between

check=('78905905f5a4ed82160c327f3fd34cba'
       '5277a9164001a4276837b59dade26af2'
       '3f8b60b6fbb993c18442b62ea661aa6b')
Run Code Online (Sandbox Code Playgroud)

数组/行总是以a)结尾,其间没有文本将包含一个闭括号.

我得到一些建议,awk可以做到这一点:

awk '/files/{
    f=0
    print $0
    for(i=1;i<=d;i++){ print a[i]  }
    g=0
    delete a # remove array after found
    next
}
/check/{ f=1; g=1 }
f{ a[++d]=$0 }
!g' file
Run Code Online (Sandbox Code Playgroud)

这只会跨越一条线.我被告知要扩大搜索范围:

awk '/source/ && /\)$/{
    f=0
    print $0
    for(i=1;i<=d;i++){ print a[i]  }
    g=0
    delete a # remove array after found
    next
}
/md5sum/ && /\)$/{ f=1; g=1 }
f{ a[++d]=$0 }
!g'
Run Code Online (Sandbox Code Playgroud)

刚学习awk所以我很感激你的帮助.或者,如果有其他工具可以做到这一点,我想听听它.有人告诉我'ed'这些类型的功能.

Dig*_*oss 2

首先回答你的最后一个问题,是的,awk这是典型的 Unix 工具,其他候选工具是非常强大的Perl,,Python或者..我最喜欢的Ruby.. 其优点之一awk是它始终存在;它是基础系统的一部分。ed(1)解决此类问题的另一种方法是使用控制或 的编辑器脚本ex(1)

好的,针对修改后的问题的新程序。该程序将根据需要向上或向下移动“检查”行,以便它们跟随“文件”行。

BEGIN {
  checkAt = 0
  filesAt = 0
  scanning = 0
}

/check=\(/ {
  checkAt = NR
  scanning = 1
}

/files=\(/ {
  filesAt = NR
  scanning = 1
}

/)$/ {
  if (scanning) {
    if (checkAt > filesAt) {
      checkEnd = NR
    } else {
      filesEnd = NR
    }
    scanning = 0
  }
}

{
  lines[NR] = $0
}

END {
  for (i = 1; i <= NR; ++i) {
    if (checkAt <= i && i <= checkEnd) {
      continue
    }
    print lines[i]
    if (i == filesEnd) {
      for (j = checkAt; j <= checkEnd; ++j) {
        print lines[j]
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)