首页 > 解决方案 > 为每个模式匹配打印 1 次出现

问题描述

我有一个文件,其中包含每个换行符开头的模式:

./bob/some/text/path/index.html
./bob/some/other/path/index.html
./bob/some/text/path/index1.html
./sue/some/text/path/index .html
./sue/some/text/path/index2.html
./sue/some/other/path/index.html
./john/some/text/path/index.html
./john/some/other/path /index.html
./john/some/more/text/index1.html
...等

我想出了以下代码来匹配 ./{name}/ 模式,并希望打印每个名称的 1 次出现,但是,它要么打印出与该模式匹配的每一行,要么只打印 1 并在使用 -m 时停止1 个标志:

我已经尝试将它作为一个简单的 grep 行(如下)并将它放在一个 for 循环中

name=$(grep -iEoha -m 1 '\.\/([^/]*)\/' ./without_localnamespace.txt)

echo $name

我的预期结果是:

./bob/
./sue/
./john/

实际结果是:
./bob/

标签: regexbashshellscriptinggrep

解决方案


awk -F'/' '!a[$2]++{print $1 FS $2 FS}' input
./bob/
./sue/
./john/

推荐阅读