提取文件名

时间:2019-06-20 20:54:33

标签: unix sed

因此,我是SED和Unix的新手,我想替换以下文件:

1500:../someFile.C:111 error
1869:../anotherFile.C:222 error
1869:../anotherFile2.Cxx:333 error
//thousands of more lines with same structure

带有followig文件

someFile.c
anotherFile.c
anotherFile2.Cxx

基本上,我只想从每一行中提取文件名。

到目前为止,我已经阅读了sed的文档和第二个答案here。我最好的尝试是使用正则表达式,如下所示:

sed "s/.\*\/.:.*//g" myFile.txt

2 个答案:

答案 0 :(得分:1)

您可以捕获最后一个/与后一个:之间的子字符串,并用捕获的字符串(\1)替换整个字符串。

sed  's#.*/\([^:]\+\).*#\1#g' myFile.txt
someFile.C
anotherFile.C
anotherFile2.Cxx

OR,转义较少,使用-r标志进行分隔。

sed -r 's#.*/([^:]+).*#\1#g' myFile.txt

或者,如果您想使用grep,则只有在您的grep支持-P标志会启用PCRE的情况下,此方法才有效:

grep -oP '.*/\K[^:]+' myFile.txt
someFile.C
anotherFile.C
anotherFile2.Cxx

答案 1 :(得分:1)

许多方法。

好的,您可以使用sed

sed 's/^[^:]*://;s/:.*//;s#\.\./##' input.txt
sed 's%.*:\.\./\([^:]*\):.*%\1%' input.txt

或者您可以在管道中使用一系列grep -o实例:

grep -o ':[^:]*:' input.txt | grep -o '[^:]\{1,\}' | grep -o '/.*' | grep -o '[^/]\{1,\}'

您甚至可以使用awk

awk -F: '{sub(/\.\.\//,"",$2); print $2}' input.txt

但是最简单的方法可能是使用cut

cut -d: -f2 input.txt | cut -d/ -f2