0

我正在使用以下命令从文件中删除注释的空行并搜索特定模式。

sed '/#/d' $file | sed '/^[  ]*$/d' | tr -d '\n' | sed -n 's/^.*tags\s*[{]\s*hosttags\s*=\s*\([0-1]\)\s*[}].*/tags {hosttags = \1}/p'

虽然上面的表达式在 shell 中对我有用,但我必须在 C 中使用它。问题出在这一行。

sprintf(buf, "sed '/#/d' %s | sed '/^[  ]*$/d' | tr -d '\n' | sed -n 's/^.*tags\s*[{]\s*hosttags\s*=\s*\([0-1]\)\s*[}].*/tags {hosttags = \1}/p'",file);

C 试图解释 \s 并且编译失败。用 [[:space]] 替换 \s 不起作用。请让我知道如何在 C 中使用它。

4

2 回答 2

1

将反斜杠加倍,更改\n\\n\sto\\s等:

sprintf(buf, "sed '/#/d' %s | sed '/^[  ]*$/d' | tr -d '\\n' | sed -n 's/^.*tags\\s*[{]\\s*hosttags\\s*=\\s*\\([0-1]\\)\\s*[}].*/tags {hosttags = \\1}/p'",file);

\\出现在 C 字符串文字中时,单个反斜杠会嵌入到字符串中的位置。

于 2013-03-14T06:57:06.050 回答
0

将 \s 替换为 POSIX 字符类 [[:space:]]。

于 2013-03-15T03:57:50.843 回答