删除字符串匹配bash的列 [英] remove columns with string match bash
问题描述
我遇到以下问题.
我需要删除文件头中包含特定字符串的列. 分号充当列限制
I need to remove columns within a file that contain a specific string in the header. The semi-colon are acting as column limit
以下示例
file 1
ADM_THO_CVL2000,ZO,AT;BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;
1;2;3;
4;5;6;
file 2
BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;ADM_THO_CVL2000,OZ,ES;BAG-AL,W,SE;
1;2;3;5;
4;5;6;7;
ADM_THO_CVL2000
是我需要删除的特定字符串.除去字符串和后续列之后的结果如下:
ADM_THO_CVL2000
is the specific string I need to remove. The results , once string and the subsequent columns are removed, are below:
BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;
2;3;
5;6;
BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;BAG-AL,W,SE;
1;2;5;
4;5;7;
我在互联网上看了看.
I had a look on the internet.
awk
可以完成我所期望的结果,但是我得到的结果却不是我期望的结果.我给你下面的代码:
awk
can do the job that but the results I'm having, are not the one that I expect. I'm giving you the code below:
awk '
FNR==1{
for(i=1;i<=NF;i++)
if ($i ~ str) {
h=(h)?h FS $i:$i
f=(f)?f FS i:i
}
print h
nf=split(f,fA,FS);next
}
{
for(i=1;i<=nf;i++)
printf("%s%c",$fA[i], (i==nf)?ORS:FS)
}' str=ADM_THO_CVL2000, 'FS=;' filename.csv
对于您的任何建议,我都很高兴.
I'm all ears for any of your suggestions.
欢呼
推荐答案
您需要在我先前的解决方案中进行一些增强.由于您无法解决该问题,因此我发布了答案:
You need some enhancements in my earlier solution. Since you could not resolve it I am posting my answer:
awk -F';' '/ADM_THO_CVL2000/{delete a; for (i=1; i<NF; i++)
if ($i ~ /ADM_THO_CVL2000/) a[i]; else printf "%s%s", $i, OFS; print $i; next}
{for (i=1; i<NF; i++) if (!(i in a)) printf "%s%s", $i, OFS; print $i }' OFS=';' file
file 1
BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;
2;3;
5;6;
file 2
BS-CCI-BAL,ARA,EL;BS-TLI-MS,ARA,BG;BAG-AL,W,SE;
1;2;5;
4;5;7;
这篇关于删除字符串匹配bash的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!