如何解决如何在awk中打印没有字段分隔符的行?
我有这样的数据(文件称为list-in.dat
)
a ; b ; c ; i
d
e ; f ; a ; b
g ; h ; i
我想要一个这样的列表(输出文件list-out.dat
),其中包含所有项目,按字母顺序(不区分大小写),每个唯一项目仅一次。
a
b
c
d
e
f
g
h
i
我的尝试是:
awk -F " ; " ' BEGIN { OFS="\n" ; } {for(i=0; i<=NF; i++) print $i} ' file-in.dat | uniq | sort -uf > file-out.dat
但是我最终得到了所有的蚁类,除了那些只有一个项的行:
a
b
c
e
f
g
h
i
无论一行中有多少个项目/如果缺少字段分隔符,如何获得所有(唯一的,已排序的)项目?
解决方法
使用gnu-awk
:
awk -F '[[:blank:]]*;[[:blank:]]*' '{
for (i=1; i<=NF; i++) uniq[$i]
}
END {
PROCINFO["sorted_in"]="@ind_str_asc"
for (i in uniq)
print i
}' file
a
b
c
d
e
f
g
h
i
对于non-gnu awk
,请使用:
awk -F '[[:blank:]]*;[[:blank:]]*' '{for (i=1; i<=NF; i++) uniq[$i]}
END{for (i in uniq) print i}' file | sort
,
awk -F' ; ' -v OFS='\n' '{$1=$1} 1' ip.txt | sort -fu
-
-F' ; '
设置空格,后跟;
,后跟空格作为字段分隔符 -
-v OFS='\n'
将换行符设置为输出字段分隔符 -
{$1=$1}
根据新的OFS更改$0
-
1
打印$0
-
sort -fu
按字母顺序唯一地忽略大小写
请您尝试遵循awk
+ sort
解决方案,并使用所示示例进行测试。如果要使用ignorecase,请在IGNORECASE=1
代码中添加awk
。
awk '
BEGIN{
FS=" ; "
}
{
for(i=1;i<=NF;i++){
if(!a[$i]++){ print $i }
}
}
' Input_file | sort
说明: 添加以上详细说明。
awk ' ##Starting awk program from here.
BEGIN{ ##Starting BEGIN section of this program from here.
FS=" ; " ##Setting field separator as space semi-colon space here.
}
{
for(i=1;i<=NF;i++){ ##Starting a for loop till NF here for each line.
if(!a[$i]++){ print $i } ##Checking condition if current field is NOT present in array a then printing that field value here.
}
}
' Input_file | sort ##Mentioning Input_file name here and passing it to sort as Input to sort the data.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。