我已经研究了好几天了,似乎无法弄清楚,我希望有人能提供帮助。我更喜欢可以在 linux 命令行中运行的答案,例如 grep、sed、awk 等。
假设我有一个名为“file.txt”的文件,其内容为:
1234jpg.jpg a.jpgbjpgy.jpg uyapss.jpg>"sdf
5678jpg.jpga.jpgbjpgy.jpg uyapss.jpg>"sdf
ABC not this line
我想做的是将所有内容提取到“.jpg”,这将给我以下结果:
1234jpg.jpg
5678jpg.jpg
我尝试过的一些命令(在数百种其他变体中)是:
cat file.txt | sed 's/\(^.*\.jpg\)/\1/'
cat file.txt | sed -e 's/^[^"jpg"]\(.*\.jpg\)/\1/'
cat file.txt | egrep '^([^jpg]*[jpg])'
cat file.txt | grep -Po '\(\K.*jpg\)'
cat file.txt | grep -Po '(?<=\.jpg).*'
我很乐意为此提供任何帮助。
肖恩
最佳答案
这可能对你有用(GNU sed):
sed 's/\(\.jpg\).*/\1/' file
或:
sed -r 's/(\.jpg).*/\1/' file
或:
sed 's/\.jpg.*/.jpg/' file
关于regex - 如何提取从行首到特定字符串的所有内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23175272/