开发者

IFS more than a character usage with R script and bash

开发者 https://www.devze.com 2023-03-31 12:55 出处:网络
I am using bash scripting to write and run R scripts: since I was not proficient in R I used to write loops and conditions in the bash script that then were translated in the R scripts or \"here docum

I am using bash scripting to write and run R scripts: since I was not proficient in R I used to write loops and conditions in the bash script that then were translated in the R scripts or "here documents"... as you can imagine the R_scripts produced in such a way becomes extremely long and difficult to be read... so I learn how to write loops and conditions with R but I found several difficulties with the command system(), so I realized that shell scripting was somehow necessary if I didn't want to get crazy with quoting and escaping... ;-) One of the first problems I faced was this: I wanted to declare a variable like this Rarr="file_1", "file_2", "file_3" ecc because I wanted to insert it in the R_script

cat>my_R_script.R<<EOF
my_arr<-c(${Rarr})
do something with my_arr
EOF

quotes are needed since if file_names were not quoted R would prompt you that it cannot find the objects named file_names

I tryed to follow the first solution in comma separated elements of array defining IFS="" ,"" but it seems that w开发者_如何转开发hen Rarr="${arr[*]}";echo "${Rarr}" the elements of arr are separated just by the first character of ${IFS}... in my case they will be separated by " is there a way to avoid this?

So basically my question is: how to force shell to consider all the characters in ${IFS} ?

anyway I found two workarounds to my problem.. the first

arr=($(ls -1 | tail))
new_IFS="\" ,\""
Rarr=${arr[0]}
for ((i=1;i<${#arr[@]};i++))
do 
    Rarr="${Rarr}${new_IFS}${arr[$i]}"
    #echo "${Rarr}"
done;
Rarr=\""${Rarr}"\"
#echo ${Rarr}

and another with parameter substitution... but I would like to know if there exist a direct solution to my problem

thank you in advance for your help


How about simply defining Rarr as Rarr="\"file_1\" \"file_2\" \"file_3\"" using the standard IFS ?


If we do without the spaces (which we don't need):

#!/bin/bash
arr=(${arr[*]/#/\"})            # prepend quotes
arr=(${arr[*]/%/\"})            # append quotes
IFS=, eval 'Rarr="${arr[*]}"'   # join by commas

(note: arr is modified).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号