leetcode 的shell部分4道题整理

对shell的某些细节还不是十分熟悉,借鉴了好多别人的东西

1. Word Frequency
 
    此题很简单,只要能排序就可以
    
    cat words.txt |tr -s " " "\n" sort | unique -c | sort -r | awk '{print $2" "$1}'
 
2. 

Valid Phone Numbers

 
cat file.txt | awk '/^\d{3}-\d{3}-\d{4}$/| /^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$/'
 
3.

Transpose File

 cat file.txt| awk '{
    max_nf = NF
    max_nr = NR
    for(x=1;x<=max_nf;x++){
        vector[x,NR]=$x;
    }
}
 
 
END{
    for(x = 1;x <= max_nf;x++){
        for( y = 1;y <= max_nr ; y++){
            printf("%s",vector[x,y])
            if (y < max_nr)  
                printf(" ")
        }
    if (x < max_nf)  
        printf("\n")
}
}
'
 
4.

Tenth Line

 cat file.txt|awk 'NR==10'
posted @ 2015-08-16 14:16  程序员小王  阅读(289)  评论(0编辑  收藏  举报