我需要从 R 中运行 awk
到 add spaces at the end of each line of a file , 以确保它始终具有固定的宽度。像这样:
$ cat -e file
1$
12$
123$
1234$
$ awk '{printf "%-10s\n", $0}' file | cat -e
1 $
12 $
123 $
1234 $
12345 $
但是,我在 R 中执行此操作时遇到了麻烦。How to correctly escape system calls from inside R处理类似的事情,但它似乎对我不起作用。
> ' awk \'{printf "%-180s\n", $0}\' file '
[1] " awk '{printf \"%-180s\n\", $0}' file "
> system(' awk \'{printf "%-180s\n", $0}\' file ')
awk: cmd. line:1: {printf "%-180s
awk: cmd. line:1: ^ unterminated string
awk: cmd. line:1: {printf "%-180s
awk: cmd. line:1: ^ syntax error
我还尝试了 system("awk '{printf\"%-180s\n\", $0}' file ")
,但出现了完全相同的错误。我不确定为什么会失败,但这似乎与混合引号有关。任何想法如何使这项工作?
最佳答案
思路是对的,只需要对\n
中的\
进行转义即可。由于它由 awk
中的 printf()
处理,因此您需要将其转义以使其按字面意思处理
system("awk '{printf \"%-10s\\n\",$0}' file")
或使用变量
awkcommand <- "awk '{printf \"%-10s\\n\",$0}' file"
system(awkcommand)
关于r - 如何在 R 中使用混合引号执行 awk 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51094930/