linux - 根据固定长度将文件中的每一行拆分为带有分隔符的子字符串

标签 linux string split offset delimiter

我需要一些帮助才能将文件转换为具有以下要求的新文件:

  1. Split each row (long string) into sub-string based on fixed length
  2. use pipe delimiter "|" between each sub-string
  3. leave last undefined column (sub-string) as-is, but add "|" before it.

这里是示例,假设文件(test.dat)有 2 行:

PG123ABCD A 000{000
MK789HJKL32H00

Column 1: length(2)
Column 2: length(3) 
Column 3: length(4)
Column 4: length(3)
Column 5: undefined, use all remaining value

下面是我需要的最终输出。该示例只有 2 行,假设我有一个包含 1k+ 相似行的文件,我需要根据上述要求将原始文件转换为新文件。

PG|123|ABCD| A |000{000
MK|789|HJKL|32H|00

最佳答案

cut -b 1-2,3-5,6-9,10-12,13-500 --output-delimiter='|' test.dat > 1.dat

我写了上面的代码,它输出的正是我需要的。

The only question I have is last column, I used 13-500 as fixed length for the undefined column, however the length of the undefined remaining string varies in different rows, is there a generic way to define the last column's length? e.g., something like 13-max_lengh_of_the_row

关于linux - 根据固定长度将文件中的每一行拆分为带有分隔符的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45338096/

相关文章:

c++ - 将字符串中的每个单词输出到一个新行

linux - 在 Linux 中,如何设置目录权限以防止用户在其中列出、删除或创建文件?

php - 通过PS查看某些运行脚本

linux - C++.a : what affects portability across distros?

java从文本文件中读取元音

php - 如何使用 PHP 分解孟加拉语文本以将所有内容保存到数据库?

mysql - 设置 crontab 以停止和启动 mysql 和 httpd 的正确方法

java - 如何将每个句子的第一个字母转换为大写并将所有其他字母转换为小写?

java - 如何使用 Java 拆分 sql 查询

java - 将字符串数组拆分为 int 数组