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

如何结合pwd与sed删除文件中包含当前工作目录的行?

问题:结合pwd与sed删除包含当前工作目录的行

给定一个存储文件路径列表的文件,需要原地删除其中包含当前工作目录的行。

示例场景

输入文件(file1)内容:

/dirA/subdir1/somefile
/dirB/subdir2/somefile
/dirB/subdir2/somefile
/dirC/subdir2/somefile
/dirD/subdir1/somefile

当前工作目录:

/dirB/subdir2/

期望编辑后file1内容:

/dirA/subdir1/somefile
/dirC/subdir2/somefile
/dirD/subdir1/somefile

之前尝试的问题分析

  • sed '/'pwd'/d' file1:路径中的斜杠/被sed当作正则表达式的分隔符,直接触发语法错误
  • sed '?'pwd'?d' file1:默认sed不支持问号?作为正则分隔符(仅GNU sed加特定参数可支持,不具备通用性)
  • sed '#'pwd'#d' file1:无效果是因为pwd输出的路径末尾带斜杠/,而文件行中的路径是目录+文件名(无尾斜杠),导致正则无法匹配到目标行

可行解决方案

方案1:sed自定义分隔符+处理尾斜杠

选择路径中不会出现的字符(比如|)作为sed的正则分隔符,同时移除pwd输出的尾斜杠,确保匹配准确:

# 先获取去掉尾斜杠的当前目录
current_dir=$(pwd | sed 's/\/$//')
# 原地删除包含当前目录的行(GNU sed)
sed -i "|$current_dir|d" file1
# 若为BSD sed(如macOS),需写成:
# sed -i '' "|$current_dir|d" file1

如果不需要处理尾斜杠(确认文件行中的路径包含带尾斜杠的目录),可直接简化为:

sed -i "|$(pwd)|d" file1

方案2:用awk替代sed

awk的变量传递更直观,无需纠结分隔符问题:

current_dir=$(pwd | sed 's/\/$//')
# 筛选不包含当前目录的行,写入临时文件后替换原文件
awk -v dir="$current_dir" 'index($0, dir) == 0' file1 > temp_file && mv temp_file file1

内容的提问来源于stack exchange,提问作者David Robie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 03:40:01