regex - 当我尝试提取正则表达式的一部分时,为什么 sed 会失败?

标签 regex linux bash sed cygwin

我的目录中有一个文件列表,这些文件具有以下命名约定:prefix_2chars_suffix
示例:currentfile_aa_belongsToprojectForDep currentfile_bb_belongsToprojectForDep
我想“提取前缀和后缀之间的2个字符。所以我想到使用sed。
我尝试了以下方法:

ls currentfile_* | sed 's/currentfile_\([..]\)_belongsToprojectForDep/\1/g'

我得到:

sed: -e expression #1, char 44: unknown command: `\'

但是当我这样做时:
echo 这是数字中的数字 7 | sed 's/digit\([0-9]\)/\1/'
它有效,这意味着我没有收到语法错误
我在这里做错了什么?

最佳答案

您不需要将它们放在[]之间:

ls currentfile_* | sed 's/currentfile_\(..\)_belongsToprojectForDep/\1/g'

您也可以只使用剪切:

ls currentfile_* | cut -f 2 -d _

更准确的形式是

ls currentfile_??_belongsToprojectForDep | cut -f 2 -d _

关于regex - 当我尝试提取正则表达式的一部分时,为什么 sed 会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18800993/

相关文章:

javascript - JS 正则表达式执行分隔符之间的内部字符串并检查损坏的分隔符

php - preg_replace 掉 CSS 注释?

linux - 不同终端的不同 nCurses 行为

linux - getpwuid() 为 LDAP 用户返回 NULL

linux - Linux 命令行上多个文件的总和列

regex - scrapy/xpaths/正则表达式 : proper xpath/re to ignore "link interjections"

java - 正则表达式获取正确的java类名

java - 为 ARM 运行 JavaFX 应用程序

使用 & 和等待在后台 bash 不同的循环

linux - 两个文件之间的差异显示空行