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

如何在Bash/Shell脚本中用Sed删除路径指定重复单词后的内容?

How to Extract the Parent Directory Path with Sed

Got it, let's first figure out why your current sed command isn't working as expected. The sed 's/config.*//' uses greedy matching—it grabs the first occurrence of "config" and everything that follows (including the second "config" in the filename), which is why you end up with /opt/xyz/ instead of the desired /opt/xyz/config/.

Here are a few reliable solutions to get the directory path you want:

Solution 1: Strip the Final Filename (Universal for Any File)

This method works no matter what the filename is—it removes everything after the last forward slash:

echo "/opt/xyz/config/config.xml" | sed 's/[^/]*$//'

How it works:

  • [^/]* matches any sequence of characters that aren't a forward slash
  • $ anchors the match to the end of the line
  • Replacing this match with an empty string deletes the filename, leaving you with /opt/xyz/config/

Solution 2: Target the Exact Filename

If you only need to handle config.xml specifically, use a precise pattern to remove just that filename:

echo "/opt/xyz/config/config.xml" | sed 's/config\.xml$//'

How it works:

  • config\.xml matches the exact filename (we escape the . with a backslash because . in regex matches any single character)
  • $ ensures we only match it at the end of the line
  • This replaces config.xml with nothing, preserving the parent directory path.

Solution 3: Non-Greedy Matching (GNU Sed Only)

If you're using GNU sed (common on Linux systems), you can use non-greedy matching to stop at the shortest possible match after "config":

echo "/opt/xyz/config/config.xml" | sed -E 's/config.*?\.xml$//'

How it works:

  • -E enables extended regular expressions
  • .*? is the non-greedy version of .*—it matches the shortest sequence instead of the longest
  • This ensures we only target the "config" in the filename, leaving the directory's "config" intact.

All three methods will give you the /opt/xyz/config/ output you're looking for. The first solution is the most flexible if you need to handle different filenames in the same directory structure.

内容的提问来源于stack exchange,提问作者Aashlesh Dhumane

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 18:35:28