简体   繁体   English

bash sed正则表达式替换未找到结果

[英]bash sed regexp replace not finding results

I have a file with rows that look like: 我有一个带有行的文件,如下所示:

mv -v DF-02239.jpg DF-02239.jpg
mv -v DF-02240.jpg DF-02240.jpg
mv -v DF-02241.jpg DF-02241.jpg
mv -v DF-02242.jpg DF-02242.jpg

I'm trying to replace the FIRST .jpg with .JPG and am using the following sed: 我正在尝试用.JPG替换FIRST .jpg并使用以下sed:

sed 's/\(mv -v .*?\)\(\.jpg\)\(.*\)/\1.JPG \3/' finalDuplicates.txt > finalCaseDuplicates.txt

I have verified the regexp works here: http://regex101.com/r/cU9xV2/1 我已经在这里验证了regexp的工作原理: http : //regex101.com/r/cU9xV2/1

You are simply replace the jpg to JPG , sed replace the first occurrence only 您只需将jpg替换为JPG, sed仅替换第一次出现的情况

sed 's/jpg/JPG/' file_name 

output 输出

mv -v DF-02239.JPG DF-02239.jpg
mv -v DF-02240.JPG DF-02240.jpg
mv -v DF-02241.JPG DF-02241.jpg
mv -v DF-02242.JPG DF-02242.jpg

Modifying your syntax just a bit: 稍微修改语法:

sed 's/\(mv -v .*\.\)jpg\(.*jpg\)/\1JPG\2/'

The trick is to involve second jpg string into equation, so that greedy sed doesn't match the whole line. 诀窍是将第二个jpg字符串包含在公式中,以使贪婪的sed与整行不匹配。

You can consider the following regex which uses a negated character class. 您可以考虑以下使用否定字符类的正则表达式。

sed 's/^\(mv -v[^.]\+\.\)jpg/\1JPG/'

Ideone Demo Ideone演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM