首页 > 解决方案 > awk 大写操作和条件匹配

问题描述

我正在尝试操作文本流,其中第二列需要小写以及第四列..(这有效)但是,在我的情况下,第五列可能有一个或多个单词..在这种情况下,我想大写第一个字母,小写单词的其余部分(或单词)

cat payload/consolidated.csv | awk -F'","|^"|"$' '{print tolower($2),"~",tolower($4),"~",toupper(substr($5,1,1)) tolower(substr($5,2))}'

但这无法将后续单词大写..它仅适用于第五列匹配中的第一个单词

想法?

同样,作为后续,我将如何为第五列设置条件 if,如果它匹配 USA(示例),我会保留它。而不是美国

赞赏。


样本数据输入

"IGNORE","Why","IGNORE","Where","FirstName LastName Country"

期望的输出

why~where~Firstname Lastname Country 

(然后我希望能够有条件地修改 Country 如果它实际上是 USA,那么我忽略 tolower() )

标签: bashawkcapitalization

解决方案


这是 GNU awk 的一个:

$ awk 'BEGIN {
    FPAT = "([^,]*)|(\"[^\"]+\")"       # using FPAT to separate fields
    OFS="~"                             # output field separator
}
{
    for(i=2;i<=NF;i++)                  # remove quotes from fields
        gsub(/^"|"$/,"",$i)         
    b=""                                # buffer the case play
    while(match($5,/ *[A-Za-z]+ */)) {  # collect the "words" and upper first char, lower rest
        b=b toupper(substr($5,RSTART,1)) tolower(substr($5,RSTART+1,RLENGTH-1)) # sorry 2Pac...
        $5=substr($5,RSTART+RLENGTH)    
    }
    print tolower($2),tolower($4),b
}' file

输出:

why~where~Firstname Lastname Country

等待那个条件套管示例。


推荐阅读