简体   繁体   English

在awk中执行IF语句

[英]Performing IF Statement in awk

I have an array of users and I need to see if the owner of a file (logfile.log) exists within the array. 我有一个用户数组,我需要查看数组中是否存在文件(logfile.log)的所有者。 Using awk I am able to pull the owner ($3) but when I use try to see if $3 is in user I get a syntax error at the beginning of my if statement. 使用awk,我可以拉出所有者($ 3),但是当我尝试查看$ 3是否在用户中时,在if语句的开头出现语法错误。 My limited understanding is that awk is not liking the syntax. 我有限的理解是awk不喜欢该语法。

user=('michael' 'mark' 'luke' 'john' 'phil' 'sam' 'kevin'); 
ls -ldL logfile.log 2>/dev/null | 
/bin/awk '{ 
    Result = $NF ":\tPermissions=" $1; 
    if ([[ "${user[*]}" =~ (^|[^[:alpha:]])$3([^[:alpha:]]|$) ]]) { 
        Result = Result "\tOwner=SUPPORT"; 
    } 
    else { 
        Result = Result "\tOwner=" $3; 
    } 
    print Result;
}'

Don't parse ls ( http://mywiki.wooledge.org/ParsingLs ). 不要解析lshttp://mywiki.wooledge.org/ParsingLs )。 Use stat to get the owner (check your stat man page, there are different implementations of different OS's) 使用stat获取所有者(请查看您的统计信息手册页,不同操作系统的实现方式有所不同)

# give your arrays a plural variable name
users=('michael' 'mark' 'luke' 'john' 'phil' 'sam' 'kevin')
owner=$(stat -c '%U' logfile.log)

if [[ " ${users[*]} " == *" $owner "* ]]; then    # spaces are deliberate
    echo logfile.log has a valid owner: $owner
else
    echo logfile.log is not owned by a valid user: $owner
fi

The other approach is to iterate over the array and look for an exact match: 另一种方法是遍历数组并查找完全匹配:

valid=false
for user in "${users[@]}"; do
    if [[ $user == $owner ]]; then
        valid=true
        break
    fi
done
if $valid; then
    echo file has a valid owner
fi

The main problem in your code is that you expect awk to understand bash syntax. 代码中的主要问题是您希望awk能够理解bash语法。 It doesn't. 没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM