【发布时间】:2015-09-06 16:59:31
【问题描述】:
任务
我正在尝试将路径名/文件名传递给 awk,以利用其字段分隔符功能。我想解析路径名/文件名以查看它是否在系统的用户目录中。示例路径:
绝对路径:
/home/students/username # VALID
/home/staff/username # VALID
/home/students/username/anythingElse # VALID
/home/staff/username/anythingElse # VALID
/home/notAccountStorage/anythingElse # INVALID
相对路径(例如,pwd/current 为 /home/student/user/courseFiles):
../ # VALID /home/student/user
../otherDir # VALID /home/student/user/other
../. # VALID /home/student/user
../.. # INVALID /home/student
../../otherDir # INVALID /home/student/otherDir
代码
我的想法是检查字符串是否以“/”开头,然后处理绝对路径,否则处理相对路径。
AWK 代码如下:
awk -F="/" ' BEGIN { directoryAccentCount=0 \
isValid=$FALSE; \
} \
{ \
# If the string starts with a "/", path is absolute \
if ( $0 ~ /^\// ) { \
# If either Student/Staff && Number of Fields must be great than 2 \
if ( ($2 == "student" || $2 == "staff") && NF > 2 ) isValid=$TRUE \
} else { \
# Path is relative \
for (i = 1; i <= NF; i++) { \
# Count how many directories the User wants to ASCEND towards ROOT \
if ( $i ~ /\.\./ ) { directoryAccentCount++ } \
# If the difference between the Number of Fields and \
# the Accent Count is greater than 2, isValid=$TRUE \
difference=(NF - $directoryAccentCount) \
if ( $difference > 2 ) isValid=$TRUE \
} \
} \
END { print $0 ":" $isValid }' << HERE $providedPath
HERE
错误
我尝试了上述代码的变体,但 awk 一直在尝试跟踪文件路径、打开文件并处理文件的文本。我想自己处理路径。
awk: fatal: 文件 `noCopyDir1' 是一个目录
【问题讨论】:
-
HERE $provicdedPath HERE需要位于 3 个单独的行上。这应该可行,但不是传统的方法。echo "$providedPATH" | awk -f ....可能会更好。然后你可以exit 0如果OK,exit 1(或其他)表示有问题。祝你好运。 -
你把 awk 和 shell 搞混了。它们是具有自己的语法和用途的独立工具。尽快获取并阅读 Arnold Robbins 撰写的《Effective Awk Programming, 4th Edition》一书,直到您没有尝试使用 awk,因为您目前从根本上误解了它。
-
@Ed Morton - 我找到了使用 awk 的解决方案的答案,我在 shell 脚本中调用它。
-
那么您找到了错误的“解决方案”,因为这不是 awk 最好解决的问题。 awk 是用于操作文本的工具。就这样。您可以修改 awk 来做其他事情,就像您可以修改 shell 来操作文本一样,但在这两种情况下,您都使用了错误的工具来完成这项工作。
-
@Ed Morton - 我愿意接受建设性的建议,为我想要完成的任务提供更好的工具。我在下面的回答可能会澄清我想要实现的目标。由于我的项目时间有限,阅读整本书并不是一个真正的选择。