我想询问如何使用 sed 和正则表达式从文件中提取特定字符串。
以下是输入文本文件(testfile.txt)的示例:
# This file contains a short description of the columns in the
# meta-analysis summary file, named '/some/output/directory/result.txt'
# (Skipping some comment lines...)
# Input for this meta-analysis was stored in the files:
# --> Input File 1 : /some/input/directory/cohort1/dataset1_chrAll.regenie.txt
# --> Input File 2 : /some/input/directory/cohort2/subdir1/chrAll-out.txt
# --> Input File 3 : /some/input/directory/cohort2/subdir2/chrAll-out_ver2.txt
# --> Input File 4 : /some/input/directory/cohort3/resfile.txt
# --> Input File 5 : /some/input/directory/cohort4/regenie_res_chrAll.txt
从这个文件,我想提取输入文件名的列表,因此结果应该是这样的:
/some/input/directory/cohort1/dataset1_chrAll.regenie.txt
/some/input/directory/cohort2/subdir1/chrAll-out.txt
/some/input/directory/cohort2/subdir2/chrAll-out_ver2.txt
/some/input/directory/cohort3/resfile.txt
/some/input/directory/cohort4/regenie_res_chrAll.txt
以下是我尝试过的:
尝试 1
这是我使用的初始命令。
cat testfile.txt | sed -e 's/\/some\/input\/directory\/([A-z0-9\/\.\-]*)\.txt/$1/g'
结果:
sed: -e expression #1, char 55: Invalid range end
尝试 2
经过一番搜索后,我尝试使用反斜杠转义括号。
cat testfile.txt | sed -e 's/\/some\/input\/directory\/\([A-z0-9\/\.\-]*\).txt/$1/g'
结果:
sed: -e expression #1, char 56: Invalid range end
所以它并没有解决问题。
尝试 3
我也尝试过转义括号。
cat testfile.txt | sed -e 's/\/some\/input\/directory\/\(\[A-z0-9\/\.\-\]\*\)\.txt/$1/g'
结果:
# This file contains a short description of the columns in the
# meta-analysis summary file, named '/some/output/directory/result.txt'
# (Skipping some comment lines...)
# Input for this meta-analysis was stored in the files:
# --> Input File 1 : /some/input/directory/cohort1/dataset1_chrAll.regenie.txt
# --> Input File 2 : /some/input/directory/cohort2/subdir1/chrAll-out.txt
# --> Input File 3 : /some/input/directory/cohort2/subdir2/chrAll-out_ver2.txt
# --> Input File 4 : /some/input/directory/cohort3/resfile.txt
# --> Input File 5 : /some/input/directory/cohort4/regenie_res_chrAll.txt
这并没有引发错误,但这不是我想要的。
尝试 4
最后,我尝试添加 -r 选项,但不转义括号或方括号。
cat testfile.txt | sed -re 's/\/some\/input\/directory\/([A-z0-9\/\.\-]*)\.txt/$1/g'
结果:
sed: -e expression #1, char 55: Invalid range end
第一次尝试时显示相同的错误消息。
我想问我的命令行中存在什么问题以及是否有任何可能的解决方案。
谢谢。
这可能对你有用(GNU sed):
使用命令行选项关闭隐式打印
-n
。使用替换命令和模式匹配,查找以 开头、
# --> Input File
后跟一个或多个数字、后跟 的行:
,然后删除该部分并打印其余部分。另一种选择:
我会怎么做:
正则表达式匹配如下:
-->
.*
\K
K
ept 是什么)作为使用后视断言的更短替代方法:环顾四周并支持正则表达式中的 \K(?:
/
[\w.-]+
)+
和
awk
:和
sed
:意思是…… “运行
sed
但不打印任何内容,除非你看到包含的行Input File
。如果看到,则将所有内容替换为冒号和空格,然后打印结果”使用 Raku/Sparrow,您可以采取增量方法,将复杂的正则表达式拆分为一系列简单的步骤(称为放大技术)