Question

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 

I have problem for pattern match to get certain details using the above details. I actually need to write down the shell script to get the following details.
I need to use pipe in this question. When I do ls -la | prog.sh it need to show the details below.
The major part I don't get is how to use sed pattern matching.
1. Total number of lines read.
2. Total number of different users (owners).
3. Total number of files with execute permission for the owner.
4. The top 3 largest directory.
This is what I have tried so far

#!/bin/bash
while read j

    do 

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



done
Was it helpful?

Solution

The while loop reads the output of ls -la line by line and you need to process each line and maintain variables for the information you need.

Here is a sample script to get you started:

#!/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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top