Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/25.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.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
Linux 如何分割unix文件中的数据_Linux_Unix_Awk_Sed_Grep - Fatal编程技术网

Linux 如何分割unix文件中的数据

Linux 如何分割unix文件中的数据,linux,unix,awk,sed,grep,Linux,Unix,Awk,Sed,Grep,我在Unix(solaris)系统中有一个包含如下数据的文件 [TYPEA]:/home/typeb/file1.dat [TYPEB]:/home/typeb/file2.dat [TYPEB]:/home/typeb/file3.dat [TYPE_C]:/home/type_d/file4.dat [TYPE_C]:/home/type_d/file5.dat [TYPE_C]:/home/type_d/file6.dat [TYPEA] /home/typeb/file1.dat [T

我在Unix(solaris)系统中有一个包含如下数据的文件

[TYPEA]:/home/typeb/file1.dat
[TYPEB]:/home/typeb/file2.dat
[TYPEB]:/home/typeb/file3.dat
[TYPE_C]:/home/type_d/file4.dat
[TYPE_C]:/home/type_d/file5.dat
[TYPE_C]:/home/type_d/file6.dat
[TYPEA]
/home/typeb/file1.dat
[TYPEB]
/home/typeb/file2.dat
/home/typeb/file3.dat
[TYPE_C]
/home/type_d/file4.dat
/home/type_d/file5.dat
/home/type_d/file6.dat
我想把下面的标题分开

[TYPEA]:/home/typeb/file1.dat
[TYPEB]:/home/typeb/file2.dat
[TYPEB]:/home/typeb/file3.dat
[TYPE_C]:/home/type_d/file4.dat
[TYPE_C]:/home/type_d/file5.dat
[TYPE_C]:/home/type_d/file6.dat
[TYPEA]
/home/typeb/file1.dat
[TYPEB]
/home/typeb/file2.dat
/home/typeb/file3.dat
[TYPE_C]
/home/type_d/file4.dat
/home/type_d/file5.dat
/home/type_d/file6.dat
具有类似类型的文件必须属于一种类型。
请帮助我在没有硬编码的情况下实现这一点的逻辑。

假设输入按类型排序,如您的示例所示

awk -F : '$1 != prev { print $1 } { print $2; prev=$1 }' file
如果有两个以上的字段,则需要调整第二个子句

sed 'H;$ !b
x
s/\(\(\n\)\(\[[^]]\{1,\}]\):\)/\1\2\1/g
:cycle
=;l
s/\(\n\[[^]]\{1,\}]\)\(.*\)\1/\1\2/g
t cycle
s/^\n//' YourFile
Posix sed版本有点不可读,因为模式中存在
[
-在标签或文件/路径中允许

-如果同一个标签之间有一行和另一个标签,则失败(示例似乎有序)。

如果可以使用
perl
,则可以使用哈希创建简单的数据结构:

#! /usr/bin/perl
use warnings;
use strict;

my %h; 

while(<>){
  chomp;
  my ($key,$value) =  split /:/;
  $h{$key} = [] unless exists $h{$key};
  push ${h{$key}},$value;

}


foreach my  $key (sort keys %h) {
  print "$key"."\n";
  foreach my $value (@{$h{$key}}){
    print "$value"."\n";
  }
}

如果您喜欢,有一个整体可以解决这个简单的问题。值得一读。

不知道Solaris上默认的Awk到底有多死板。您可能想尝试使用
nawk
mawk
,或者如果您的Solaris Awk开箱即用的脚本有问题,可以寻找XPG Awk。