运行awk脚本后截断字符串 [英] Truncation of strings after running awk script
问题描述
我有这个代码
BEGIN { FS=OFS=";" }
{ key = $(NF-1) }
NR == FNR {
for (i=1; i<(NF-1); i++) {
if ( !seen[key,$i]++ ) {
map[key] = (key in map ? map[key] OFS : "") $i
}
}
next
}
{ print $0 map[key] }
我以这种方式使用代码
awk -f tst.awk 2.txt 1.txt
我有两个文本文件
1 .txt
AA;BB;
2 .txt
CC;DD;BB;AA;
我尝试生成此 3 .txt输出
I try to generate this 3.txt output
AA;BB;CC;DD;
但无法使用此脚本,因为此脚本仅返回 AA; BB;
but with this script is not possible because this script return only AA;BB;
逻辑:上面的代码仅在数组索引的哈希查找中使用文字字符串,因此它不在乎输入中包含哪些字符.但是关于示例输出:
如果在 2 .txt中, 1 .txt中也有一些公共字段,例如 BB; AA;
那么您需要将它们连接在一行中,即 AA; BB; CC; DD;
不需要排序,例如,如果输出为 BB; AA; DD; CC;
唯一需要的条件是避免重复,但是我的脚本已经这样做了
logic: The above just uses literal strings in a hash lookup of array indices so it doesn't care what characters you have in your input. However about sample output:
if in 2.txt there are common fields also in 1.txt.for example BB;AA;
then you need concatenate them in a single row, i.e AA;BB;CC;DD;
Ordering is not required, for example is not relevant if output is BB;AA;DD;CC;
Only condition that is required is avoid duplicates but my script already does this
推荐答案
能否请您尝试以下操作,根据OP的注释,两个文件只有1行.因此,使用 paste
命令合并两个文件,然后通过 awk
命令处理其输出.
Could you please try following, as per OP's comment both files have only 1 line. So using paste
command to combine both the files and then processing its output by awk
command.
paste -d';' 1.txt 2.txt |
awk '
BEGIN{
FS=OFS=";"
}
{
for(i=1;i<=NF;i++){
if(!seen[$i]++){ val=(val?val OFS:"")$i }
}
print val
delete seen
val=""
}'
这篇关于运行awk脚本后截断字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!