gpt4 book ai didi

awk - 获取唯一的字符串出现并显示它

转载 作者:行者123 更新时间:2023-12-05 09:07:40 27 4
gpt4 key购买 nike

我不太擅长 awk,所以这里是我计算一行中出现次数的方法:

input.txt 有这个:

18 18 21 21 21 21 18 21

我只想显示上面出现的唯一编号。所以,这是我的代码:

input="input.txt"

output=$(fmt -1 "$input" | sort | uniq | awk '{printf $1","}')

echo "$output"

输出:

18,21,

我得到了正确的结果,但是最后那个逗号,,我该如何删除那个逗号?另外,是否有不使用 fmt 的更简单或干净的方法?

预期输出:

18,21

编辑删除逗号,我用这个:

sed 's/,$//'

它正在运行,但是有没有更简单的方法可以在不使用 fmt 的情况下做到这一点?

最佳答案

能否请您尝试以下。

awk '
BEGIN{ OFS="," }
{
for(i=1;i<=NF;i++){
if(!arr[$i]++){
val=(val?val OFS:"")$i
}
}
print val
val=""
}' Input_file

说明: 为以上添加详细说明。

awk '                          ##Starting awk program from here.
BEGIN{ OFS="," } ##Setting output field separator as comma here.
{
for(i=1;i<=NF;i++){ ##Traversing through all fields of currnet line here.
if(!arr[$i]++){ ##Checking condition if arr is NOT having current field present in it
val=(val?val OFS:"")$i ##Creating val and keep adding values to it, to print at last all values.
}
}
print val ##printing val here.
val="" ##Nullify val here.
}' Input_file ##mentioning Input_file name here.

关于awk - 获取唯一的字符串出现并显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64693124/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com