linux shell(leetcode)

来源:互联网 发布:淘宝网商城女装针织衫 编辑:程序博客网 时间:2024/06/05 12:02

194 Transpose File(leetcode)

https://leetcode.com/problems/transpose-file/

解析参考:http://www.cnblogs.com/grandyang/p/5382166.html


file.txt (2行3列)

name agealice 21ryan 30

awk '{    for (i = 1; i <= NF; ++i) {        printf("%d ",i);    }}' file.txt

打印出 1 2 1 2 1 2
说明 执行了3次for,每次for 循环两次(NF表示列数,有两列)


$1 可以打印第一列的值,$2可以打印第2列的值

用一个数组 s[1]存第一列,s[2]存第二列

awk '{    for (i = 1; i <= NF; ++i) {        if(NR == 1)                s[i] = $i;        else                s[i] = s[i] " " $i;    }}END{        for(i = 1; i <= NF; ++i)                printf("%s\n", s[i]);}' file.txt

实现转置 打印出
name alice ryan
age 21 30


192 Word Frequency

https://leetcode.com/problems/word-frequency/

words.txt

the day is sunny the thethe sunny is is

output(sorted by descending frequency)

the 4is 3sunny 2day 1

ac

cat words.txt| tr -s ' ' '\n' | sort -r | uniq -c | sort -rn | awk '{print $2 " " $1}'

参考:
在线疯狂
http://bookshadow.com/weblog/2015/03/24/leetcode-word-frequency/

主要命令

tr / sed
sort
uniq
awk


0 0
原创粉丝点击