【问题标题】:`sed` pattern matching?`sed` 模式匹配?
【发布时间】:2014-06-17 17:09:16
【问题描述】:
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

【问题讨论】:

  • @hek2mgl 上面显示。我做过的很少
  • 查看您的编号列表,我敢打赌将ls 输出写入文件然后greping、awking(或cuting)、@987654329 会更快@ing (-c) 和 sorting 从中取出数据。对不起很多ings :)

标签: linux bash shell sed command


【解决方案1】:

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"

【讨论】:

  • sed 在这里不合适,因为您正在进行逐行处理。
猜你喜欢
  • 2022-01-12
  • 2021-05-23
  • 1970-01-01
  • 2016-05-18
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 2020-08-04
  • 2022-01-13
相关资源
最近更新 更多