问题描述
我愿意比较 R中的两个路径(分别命名为
,使用 a
和 b
) Bash
中的 diff
命令。
I was willing to compare two paths (named a
and b
) in R
using the diff
command from Bash
.
在bash中我会做
$ a=Path/to/foo/directory/
$ b=Path/to/bar/directory/
$ diff <(printf ${a} | tr / '\n') <(printf ${b} | tr / '\n')
3c3
< foo
---
> bar
所以从RI正在尝试
a="Path/to/foo/directory/"
b="Path/to/bar/directory/"
system(
paste0(
"a=",a,
";b=",b,
";diff <(printf ${a} | tr / '\n') <(printf ${b} | tr / '\n')"
)
)
OR
system(
paste0(
"diff <(printf ",a," | tr / '\n') <(printf ",b," | tr / '\n')"
)
)
,但都返回错误。
sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `a=Path/to/foo/directory/;b=Path/to/bar/directory/;diff <(printf ${a} | tr / ''
即使复制粘贴了输出在bash中使用 paste0
函数可以正常工作。
even though copy-pasting the output of the paste0
function into bash works fine.
在R中比较字符串可能会有更好的方法,我也欢迎使用替代方法解决方案,但是,我参与其中对了解我对 system()
函数的用法有什么问题以及如何解决它很感兴趣。
There might be better ways to compare strings in R and I would welcome alternative solutions. However, I am particularly interested in understanding what is going wrong with my usage of the system()
function and how to solve it.
推荐答案
如,系统(..)
未运行 / usr / bin / bash
,但 / usr / bin / sh
。这是解决该问题的两种可能的解决方案。
As explained here, system(..)
is not running /usr/bin/bash
but /usr/bin/sh
. Here are two possible solutions to the problem.
usr / bin / sh中的解决方案
因此,要使脚本通过 / usr / bin / sh
运行,我必须在文件上打印字符串。
So in order to make a script that run through /usr/bin/sh
I had to print strings on files.
DiffPath = function(a,b,ManipulationFolder="~")
{
if (file.exists(ManipulationFolder))
{
system(
paste0(
"cd ",ManipulationFolder,
";a=",a,
";b=",b,
";printf ${a} | tr / '\n' > a.txt",
";printf ${b} | tr / '\n' > b.txt",
";diff a.txt b.txt",
";rm a.txt;rm b.txt"
)
)
} else
{
warning(paste0("Cannot find the ManipulationFolder ( ",ManipulationFolder," )"))
}
}
usr / bin / bash中的解决方案
一种更好的选择解决方案是显式地执行bash命令。
An alternative and nicer solution is to explicitly give the command to bash.
DiffPath = function(a,b)
{
system(
paste0(
'bash -c \'diff <(printf ',a,' | tr / "\n") <(printf ',b,' | tr / "\n")\''
)
)
}
函数调用
a="Path/to/foo/directory/"
b="Path/to/bar/directory/"
DiffPath(a,b)
3c3
< foo
---
> bar
这篇关于通过`system(..)`使用R中的`diff`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!