You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求sed正则替换方案:仅修改文件名任意位置而非路径

Solution for sed Replace in Filename (Any Position)

First, let's fix your sed expression to target substrings anywhere in the filename while preserving the full path, and still print both the original and modified lines. Here's the corrected pattern:

sed 'p;s;\(.*/\)\(.*\)SubstringToFind\(.*\);\1\2SubstringToInsert\3;'

Why Your Original Pattern Failed

Your original regex \(.*/\)SubstringToFind only matches cases where SubstringToFind is at the very start of the filename (right after the path separator /). It doesn't account for any characters that might come before the target substring in the filename.

Breakdown of the Corrected Pattern

Let's break down how this new expression works step by step:

  • p: Prints the original input line first (just like your original command)
  • s;...;...;: The substitution command, using ; as a delimiter to avoid conflicts with path slashes
    • \(.*/\): Captures the full path (everything up to and including the final /) into group 1
    • \(.*\): Captures any characters in the filename that come before your target substring into group 2
    • SubstringToFind: The specific substring you want to replace in the filename
    • \(.*\): Captures any characters in the filename that come after your target substring into group 3
    • \1\2SubstringToInsert\3: Reconstructs the path+filename:
      • \1: The unmodified path from group 1
      • \2: The characters before the target substring (from group 2)
      • SubstringToInsert: Your replacement text
      • \3: The characters after the target substring (from group 3)

Example Tests

Let's verify this with your sample cases to confirm it works as expected:

Case 1: Replace leading t in filename

Input: ./test.c
Command:

sed 'p;s;\(.*/\)\(.*\)t\(.*\);\1\2###\3;'

Output:

./test.c
./###est.c

✅ Matches your expected result.

Case 2: Replace leading tes in filename

Input: testdir/test.c
Command:

sed 'p;s;\(.*/\)\(.*\)tes\(.*\);\1\2#\3;'

Output:

testdir/test.c
testdir/#t.c

✅ Matches your expected result.

Case 3: Replace middle est in filename

Input: ./test.c
Command:

sed 'p;s;\(.*/\)\(.*\)est\(.*\);\1\2#\3;'

Output:

./test.c
./t#.c

✅ Now produces your desired result (previously failed with your original pattern).

Content from Stack Exchange, asked by Gregalor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:07:09