`sed`模式匹配?

时间:2014-05-01 07:55:40

标签: linux bash shell sed command

Permissions   links  Owner  Group  Size   Date        Time    Directory or file
-rwxr--r--     1     User1  root    26    2012-04-12  19:51    MyFile.txt
drwxrwxr-x     3     User2  csstf  4096   2012-03-15  00:12     MyDir 

我有模式匹配的问题,使用上述细节获取某些细节。我实际上需要写下shell脚本来获取以下细节。
我需要在这个问题中使用管道。当我ls -la | prog.sh时,需要在下面显示详细信息。
我不了解的主要部分是如何使用sed模式匹配。
1.读取的总行数。
2.不同用户(所有者)的总数。
3.拥有所有者执行权限的文件总数。
4.前三大目录。
这是我到目前为止所尝试的内容

#!/bin/bash
while read j

    do 

        B=`sed -n '$=' $1`
        echo "total number of lines read = $B"



done

1 个答案:

答案 0 :(得分:0)

while循环逐行读取ls -la的输出,您需要处理每一行并维护变量以获取所需信息。

以下是一个示例脚本,可帮助您入门:

#!/bin/bash
declare -i lineCount=0
declare -i executePermissionCount=0

# an array to keep track of owners
declare -a owners=()


# read each line into an array called lineFields
while read -r -a lineFields
do
    # the owner is the third element in the array
    owner="${lineFields[2]}"

    # check if we have already seen this owner before
    found=false
    for i in "${owners[@]}"
    do
        if [[ $i == $owner ]]
        then
            found=true
        fi
    done

    # if we haven't seen this owner, add it to the array
    if ! $found
    then
        owners+=( "$owner" )
    fi


    # check if this file has owner execute permission
    permission="${lineFields[0]}"
    # the 4th character should be x
    if [[ ${permission:3:1} == "x" ]]
    then
        (( executePermissionCount++ ))
    fi

    # increment line count
    (( lineCount++ ))
done
echo "Number of lines: $lineCount"
echo "Number of different owners: ${#owners[@]}"
echo "Number of files with execute permission: $executePermissionCount"