如何在Bash/Shell脚本中用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\.xmlmatches 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.xmlwith 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:
-Eenables 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

