我的目录中有一个文件列表,这些文件具有以下命名约定: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/