linux - 使用 tac 反向读取文件

标签 linux file unix reverse gnu-coreutils

我是 UNIX 编码的新手,我有一个文件需要逐行反向读取。该文件在 {} 中有代码段。然后我需要使用这个反向文件作为输入来运行一个 awk 脚本。我正在让我们的支持人员安装 tac,但在他们安装之前,我想知道它是否会输出我需要的内容,或者是否有人可以建议替代方案。

该文件包含以下形式的数据:

page 0 0 0 none
{
   layer 0 0 0 "1line" 0 8 8 3
   {
      sector 0 -1 0 32 
      {
        point_name 0 0 34543 34 44 1 1 0
        status 1 0 1 0 1 431232 "transformer" 23 12
        analog 1 0 1 0 1 321234 11.5 43 1 1 0
        ...
        ...
        ...
        device 1 0 1 "ground" 32 56 1 1 0
      }
    }
}

我想保留 {} 但反转 {} 之间的线条,这样输出看起来像:

page 0 0 0 none
{
   layer 0 0 0 "1line" 0 8 8 3
   {
      sector 0 -1 0 32 
      {
        device 1 0 1 "ground" 32 56 1 1 0
        ...
        ...
        ...
        analog 1 0 1 0 1 321234 11.5 43 1 1 0
        status 1 0 1 0 1 431232 "transformer" 23 12
        point_name 0 0 34543 34 44 1 1 0
      }
    }
}

此外,tac 是覆盖输入文件还是将其保存为不同的文件?

最佳答案

像大多数 UNIX (style) 工具一样,tac 既不覆盖原始文件也不写入新文件,它打印到 stdout,以写入一个带有 tac 的新文件 您将使用重定向 tac file > newfile 这会将反转的 file 保存到 newfile 中。单独使用 tac 无法完成您需要的操作,您需要一个脚本。

这是 awk 中的一个:

{
    # store each line in the array line
    line[n++] = $0
} 

/{/ {
    # get the line number of the last line containing {
    first=NR
}

!/}/ {
    # get the line number of the last line not containing }
    last=NR
} 

END {
    # print first section in order
    for (i=0;i<first;i++) 
        print line[i]
    # print second section in reverse order
    for (i=last-1;i>=first;i--)    
        print line[i]
    # print last section in order
    for (i=last;i<NR;i++) 
        print line[i]
}

将其保存到文件中说 reverse 然后运行 ​​awk -f reverse file:

$ awk -f reverse file
page 0 0 0 none
{
   layer 0 0 0 "1line" 0 8 8 3
   {
      sector 0 -1 0 32 
      {
        device 1 0 1 "ground" 32 56 1 1 0
        ...
        ...
        ...
        analog 1 0 1 0 1 321234 11.5 43 1 1 0
        status 1 0 1 0 1 431232 "transformer" 23 12
        point_name 0 0 34543 34 44 1 1 0
      }
    }
}

使用重定向创建一个新文件awk -f reverse file > newfile

关于linux - 使用 tac 反向读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14258616/

相关文章:

linux - 我如何获得昨天的日期

linux - 如何摆脱期望: spawn id exp7 not open

linux - 操作系统中的任何命令如何工作?

c - select() 函数的第一个参数到底是什么

linux - 识别单个 unix 目录中文本文件中的模式

linux - 如何测试用crontab部署的脚本

arrays - 用C在数组中移动指针

php - HTML表单文件上传不起作用,$_POST不转发数据

java - file.delete() 是否为不存在的文件返回 true 或 false?

linux - 在 bash 或 zsh 中别名 anything=<C-a >"sudo "