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.前3个最大的目录。
到目前为止,这是我尝试过的

#!/bin/bash
while read j

    do

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



done

最佳答案

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"

关于linux - sed模式匹配?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23404029/

10-11 19:14