wthimdh
wthimdh

Reputation: 486

How to add a line with increasing numbers to a txt file using bash

I want to add a line such as :

Var1 <- rbind(x1, x2, x3, x4, x5, x6)

to a txt file. User will specify the numbers. If script is run as ./script.bash 2 7 text file should have the following line:

Var1 <- rbind(x2, x3, x4, x5, x6, x7)

Here's what I've tried so far:

#!/bin/bash
beg=$1
last=$2
echo "Var1 <- rbind(???) " > output.txt

Is there an easy way to do this with bash?

Upvotes: 0

Views: 163

Answers (3)

Lars Fischer
Lars Fischer

Reputation: 10209

Here is something built around the seq command:

script.sh

#!/bin/bash
echo "var1 <- rbind(x"$(seq -s", x" $1 $2 )")" >> "output.txt"

seq arg1 arg2 creates the sequence of numbers between arg1 and arg2 and the -s argument let us specify the delimiter string used.

The output of e.g. seq -s ", x" 1 7 is 1, x2, x3, x4, x5, x6, x7 and we concatenate with the constant strings var1 <- rbind(x and ).

Upvotes: 2

Tom Fenech
Tom Fenech

Reputation: 74685

I guess it depends what you would describe as an easy way to do this but here's one option:

#!/bin/bash

beg=$1
end=$2

{
    printf 'Var1 <- rbind('
    for (( i = beg; i < end; ++i )); do 
        printf '%d, ' "$i"
    done
    printf '%d)\n' "$end"
} > output.txt

Loop through the numbers, adding the commas between. Redirect the output of the block to the file.

Upvotes: 1

redneb
redneb

Reputation: 23870

Something like should work:

#!/bin/bash
first=$1
last=$2
(
  echo -n "Var1 <- rbind("
  for n in $(seq "$first" $((last-1))); do
      echo -n "x$n, "
  done
  echo "$last)"
) >> "output.txt"

I am using a for loop to create the list of arguments (i.e. xN). The whole loop as well the other two statements that print the prefix and suffix of the line, are all run from within a subshell that is redirected to the file.

Upvotes: 1

Related Questions