【发布时间】:2020-03-01 11:33:06
【问题描述】:
我有一个文件有很多行是这样写的 -
random text
some info, command -task shoot and more info
some info, command -new_task shoot and more info
more info and shoot a lot
command -task shoot and some more info and shoot a lot
我希望shoot 的首字母大写,command -* shoot 除外。
所以替换后我的文件应该是这样的 -
random text
some info, command -task shoot and more info
some info, command -new_task shoot and more info
more info and Shoot a lot
command -task shoot and some more info and Shoot a lot
我为此编写了以下脚本 -
var="shoot";
sed -i "/-.*?${var}/ ! s/ ${var} / ${var^} /g" file;
除了command -* shoot 和shoot 写在同一行之外,这个脚本工作正常。在这种情况下,我得到的输出为 -
command -task Shoot and some more info and Shoot a lot
在这种情况下,shoot 都成为大写字母,这是不可取的。
有什么办法可以解决这个问题吗?
【问题讨论】:
-
command -后面可以有哪些字符?除了空间或特定集合之外的一切? -
只有一组特定的字符:-task、-start_task 和 -end_task,但我正在考虑编写更通用的 sed 命令形式。无论如何,如果只有这 3 种情况,解决办法是什么?
-
我可能会像
sed 's/shoot/\u&/g; s/\(command -[^ ]* \)Shoot/\1shoot/g' file那样做某事,但我并不是说这是最好的方法 -
谢谢@oguzismail。这非常有效,我想不出比这更好的解决方案。