我想在文件中替换所有出现的字符串,如下所示:
printf("thread %d: enters barrier at %d and leaves at %d\n", MYTHREAD, start, end);
带
printf("thread %d: enters barrier at %lf and leaves at %dlf\n", MYTHREAD, (double)start, (double)end);
我一直在尝试的命令是
perl -pi -e "s/printf(\"thread %d: enters barrier at %d and leaves at %d\\\n\", MYTHREAD, start, end);/printf(\"thread %d: enters barrier at %lf and leaves at %lf\\\n\", MYTHREAD,(double)start/CLOCKS_PER_SEC, (double)end/CLOCKS_PER_SEC)/g" bt_copy.c
但我得到错误。有谁可以指出我哪里出错?
答案 0 :(得分:3)
您使用斜杠/
字符作为s///
表达式的分隔符,但您的替换模式中也包含斜杠字符
printf(\"thread %d: enters barrier at %lf and leaves at %lf\\\n\",
MYTHREAD,(double)start/CLOCKS_PER_SEC, (double)end/CLOCKS_PER_SEC)
您可以尝试使用其他分隔符,例如
perl -pi -e 's! ...pattern ... ! ...replace ...!g' input_file
(另外如果你使用像bash这样的Unixy shell,在指定你的单行程序时更喜欢使用单引号加双引号。那么你将会有更少的shell元字符插值相关的头痛。)
答案 1 :(得分:2)
从C的角度来看,考虑以下优点:
void pr_barrier_time(int thread, int start, int end)
{
printf("thread %d enters barrier at %lf and leaves at %lf\n",
thread, (double)start/CLOCKS_PER_SEC, (double)end/CLOCKS_PER_SEC);
}
编辑你的代码,使调用成为:
pr_barrier_time(MYTHREAD, start, end);
您甚至可以在'printf()'之后使用函数调用添加自动'fflush()';使用内联printf()
语句更加难以理解。
答案 2 :(得分:0)
这应该可以使用sed
执行您想要的操作。
sed 's/printf("thread %d: enters barrier at %d and leaves at %d\\n", MYTHREAD, start, end);/printf("thread %d: enters barrier at %lf and leaves at %dlf\\n", MYTHREAD, (double)start, (double)end);/' bt_copy.c