[英]How to print a line with no field separator in 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'; '
-F'; '
设置空格,后跟;
后跟空格作为字段分隔符-v OFS='\n'
设置换行符为 output 字段分隔符{$1=$1}
根据新的 OFS 更改$0
1
打印$0
sort -fu
按字母顺序唯一地忽略大小写 您能否尝试以下awk
+ sort
解决方案,使用所示样本编写和测试。 如果您想使用忽略大小写,请在awk
代码中添加IGNORECASE=1
。
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.