LeetCode:Shell题目

题目一:Tenth Line

输出文件的第10行

方法一:bash

#!/bin/bash
var=1
while read line && [ $var -le 10 ]
do
    if [ $var -eq 10 ]
    then
        echo $line
        exit 0
    fi
    let var++
done < file.txt

方法二:tail与head组合

tail -n +10 file.txt | head -n 1

方法三: awk

awk 'FNR == 10 {print }'  file.txt

方法四:sed

sed -n 10p file.txt

题目二:Transpose File

将文本的行变成列列变成行
方法一:awk

awk '
    {
        for(i=1;i<=NF;i++)
        {
            if(line[i]=="")
            {
                line[i]=$i
            }
            else
            {
                line[i]=line[i]" "$i
            }
        }
    }
    END{
        for(i=1; i<=NF ;i++)
        {
            print line[i]
        }
    }
    ' file.txt

方法二:bash

array=()

while read -a columns; do
    for (( i = 0; i < ${#columns[@]}; i++ )); do
        array[i]="${array[i]} ${columns[i]}"
    done
done < file.txt

for (( i = 0; i < ${#array[@]}; i++ )); do
    echo ${array[i]}
done

题目三:Valid Phone Numbers

判断是否是合法的电话号码
方法一:grep

grep -P '^(\d{3}-|\(\d{3}\) )\d{3}-\d{4}$' file.txt

方法二:awk

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

方法三:sed

sed -n -r '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/p' file.txt

题目四:Word Frequency

统计单词的频率,降序输出
方法一:awk

awk '
{
    for(i=1;i<=NF;i++)
        words[$i]++

} 
END{
    for(word in words)
    {
        print word,words[word]

    }

}' RS="[ \n]+" words.txt  | sort -nrk2

你可能感兴趣的:(Linux,剑指Offer)