sed - 在sed中获取过滤部分的第一个字母

标签 sed

我有一个文件名,例如15736--1_brand-new-image.jpg

我的目标是获取 _ 之后的第一个字母,在本例中是 b

使用 s/\(.*\)\_\(.*\)$/\2/ 我能够提取 brand-new-image.jpg

部分基于在 https://www.oncrashreboot.com/use-sed-to-split-path-into-filename-extension-and-directory 上找到的信息

我已经找到了 get first letter of words using sed但未能将两者结合起来。

为了验证我的 sed 语句,我使用了 https://sed.js.org/

如何在过滤的部分组合新的 sed 语句以获得第一个字母?

最佳答案

请根据您展示的示例尝试以下操作。

echo "15736--1_brand-new-image.jpg" | sed 's/[^_]*_\(.\).*/\1/'

解释: 简单地使用 sed 的替换操作,然后查找第一个出现的 _ 然后保存下一个将 1 个字符放入后向引用并提及 .* 将涵盖其后的所有内容,而只需将所有内容替换为第一个后向引用值,该值将在第一个 _ 之后,在本例中为 b

说明:以下仅作说明之用。

sed '            ##Starting sed program from here.
s/               ##using s to tell sed to perform substitution operation.
[^_]*_\(.\).*    ##using regex to match till 1st occurrence of _ then using back reference \(.\) to catch value in temp buffer memory here.
/\1/             ##Substituting whole line with 1st back reference value here which is b in this case.
'

关于sed - 在sed中获取过滤部分的第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66493008/

相关文章:

shell - 如何在模式前面插入换行符?

linux - sed 和变量替换

linux - 使用sed命令执行脚本的查询

bash - sed 编辑 csv 文件中的特定列和行

linux - 有人可以解释为什么 sed 在执行 'sed x file.txt' 时会出现这种行为吗?

regex - 无法弄清楚如何使用 AppleScript 实现 REGEX

bash - 使用管道逃逸

regex - 将 sed 与正则表达式一起使用

bash - 如何根据条件从数据 block 中获取特定数据

sed - 如何理解带有复杂替换的 sed?