简体   繁体   中英

bash: create variable by concatenating N strings, where N is a script argument

Suppose I have a bash script, myscript.sh , that takes 2 numbers, N and P, as arguments - ie, I'd run it like this: sh myscript.sh 3 4

Inside the script, I'd like to run a program that takes a list of comma-separated files as arguments. N denotes the number of elements in that list. I need to construct this list of file paths, differentiated by a sample number running from 1 to N . It's easier to see with an example:

#!/bin/sh

myProgram -p $1 -f /home/folder/sample01.R,/home/folder/sample02.R,/home/folder/sample03.R 

I'm struggling to create that comma-separated list of files given only N (3) as input. Is there a good way to create a variable holding the string /home/folder/sample01.R,/home/folder/sample02.R,/home/folder/sample03.R as a function of 3?

I've had success creating a variable holding 01,02,03 using seq , but have not been able to figure out how to attach the file paths to those numbers. (I'm getting stuck due to the fact that brace expansion happens before variable evaluation -- so, setting X= 'seq -f %02.0f 1 $N' and doing a{$X}b does not give a01b a02b a03b as I'd hoped, and even if it did, I'm not sure how I'd generate a01b,a02b,a03b from that.). Another snag is that I'm not using bash 4, so {00..09} gives a sequence of numbers that are NOT zero-padded (which causes problems). I developed a workaround with Python, but I'd love to be able to do it in bash to avoid having to call an external script.

Any and all suggestions appreciated!

You can construct your string using a number N like this:

N=3
s=""
for ((n=1; n<=N; n++)); do
    [[ -n "$s" ]] && s="$s,"
    printf -v s "%s/home/folder/sample%02d.R" "$s" "$n"
done

echo "$s"
/home/folder/sample01.R,/home/folder/sample02.R,/home/folder/sample03.R

If I were you, I'd have a look at the printf built-in:

f=$(printf "/home/folder/sample%02d.R" $num) 

If you put this in a loop you will have your properly formatted numbers.

To create the comma-separated list, you can just append each filename to a string with a comma:

files="$files, $f"

After the loop, you just need to remove the first character from the string (it's a surplus comma), and you're done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM