bash - 动态提取 bash 中字符串列表中每个字符串唯一的模式

标签 bash perl awk pattern-matching

我正在尝试从 bash 中的文件名列表中动态提取独特的模式。

输入的文件名列表如下所示

Exp1_ML_Rep1.txt,Exp1_ML_Rep2.txt,Exp1_ML_Rep3.txt

我想动态提取字符串

Rep1,Rep2,Rep3

此处以图表方式显示:

Example1

注意:输入模式每次都可能改变 例如另一个用例可能是

Exp2_DT_10ng_55C_1_User1.png,Exp2_DT_10ng_55C_2_User1.png,Exp2_DT_10ng_55C_3_User1.png

在这种情况下,我想提取

1,2,3

此处以图表方式显示:

Example2

在 bash 中实现此目的的最佳方法是什么?


按照评论中的建议,我尝试了以下方法:

declare -p string1 string2

declare -- string1="ER_Rep1"
declare -- string2="ER_Rep2"

diff <(echo "$string1" ) <(echo "$string2") 返回

1c1 
< ER_Rep1 
--- 
> ER_Rep2

我要提取的是 Rep1,Rep2。

最佳答案

您可以将 GNU awksortuniq 结合使用

echo 'Exp1_ML_Rep1.txt,Exp1_ML_Rep2.txt,Exp1_ML_Rep3.txt' | awk -v RS='[_.,]' '1' | sort | uniq -u

tr 结合 sort & uniq

echo 'Exp1_ML_Rep1.txt,Exp1_ML_Rep2.txt,Exp1_ML_Rep3.txt' | tr '_.,' '\n' | sort | uniq -u

产生输出

Rep1
Rep2
Rep3

关于bash - 动态提取 bash 中字符串列表中每个字符串唯一的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68274814/

相关文章:

awk - 从 AWK 字段打印不同的值

linux - 如何在 Linux 中 grep 特定时间戳范围内的日志文件内容?

linux - Grep 文本的特定部分

linux - 为什么我收到 IO::Uncompress::Unzip::unzip: input filename is undef or null string 消息?

perl - move 文件时未定义的子例程

庆典/sed/awk : change first alphabet in string to uppercase

bash - 替换文本文件中的日期

linux - 将大文件拆分为较小的文件,每个文件中有 n 行

python - 为什么我们在 Perl 中需要两个相等运算符 ("=="和 "eq")?

regex - 使用 awk 正则表达式捕获插入符号 (^)