我现在有一段代码:
read -p 'Enter the fruit you want to search: ' user_fruit
awk -F ":" -v re="$user_fruit" '$4 ~ re' $fruit_file它使用awk在$4中查找与用户在$fruit_file中的$user_fruit变量下提供的模式匹配的匹配。但是,我需要修改awk命令,以便它只在单词apple也在行上时显示行匹配。
任何帮助都将不胜感激!
发布于 2021-05-06 08:21:43
您可以使用布尔运算符扩展awk模式:
read -p 'Enter the fruit you want to search: ' user_fruit
awk -F ":" -v re="$user_fruit" '/apple/ && $4 ~ re' "$fruit_file"即,当记录与/apple/匹配时打印记录,第四个字段与regex匹配。
发布于 2021-05-06 09:05:43
如果您想检查是否存在文字的、固定的字符串,您可以使用index代替regex搜索:
read -p 'Enter the fruit you want to search: ' user_fruit
awk -F ":" -v re="$user_fruit" 'index($0, "apple") && index($4, re)' file这里,
index($0, "apple") -检查整行中是否存在apple子字符串(如果其索引不是0)&& - AND条件index($4, re) -检查字段4中是否存在apple子字符串(如果其索引不是0)。见在线演示
s='one:two:three:2-plum+pear
apple:two:three:1-plum+pear'
user_fruit='plum+pear'
awk -F ":" -v re="$user_fruit" 'index($0, "apple") && index($4, re)' <<< "$s"
#index($3, "snow") != 0
# => apple:two:three:1-plum+pearhttps://stackoverflow.com/questions/67414310
复制相似问题