问题
I was willing to compare two paths (named a
and b
) in R
using the diff
command from Bash
.
In bash I would do
$ a=Path/to/foo/directory/
$ b=Path/to/bar/directory/
$ diff <(printf ${a} | tr / '\n') <(printf ${b} | tr / '\n')
3c3
< foo
---
> bar
So from R I am trying
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')"
)
)
but both return an error.
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 / ''
even though copy-pasting the output of the paste0
function into bash works fine.
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.
回答1:
As explained here, system(..)
is not running /usr/bin/bash
but /usr/bin/sh
. Here are two possible solutions to the problem.
Solution in "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," )"))
}
}
Solution in "usr/bin/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")\''
)
)
}
Function call
a="Path/to/foo/directory/"
b="Path/to/bar/directory/"
DiffPath(a,b)
3c3
< foo
---
> bar
来源:https://stackoverflow.com/questions/39128344/using-diff-from-r-via-system