rfc1484
rfc1484

Reputation: 9837

Bash script for creating text in a file using arguments

Imagine that you have to create many lines in file all with the same text except for one variable:

foo text $variable bar text
foo text $variable bar text
foo text $variable bar text
...

I was wondering if this could be made using a bash script passing it the variable as an argument:

./my_script '1'
./my_script '2'
./my_script '3'

Which would generate this:

foo text 1 bar text
foo text 2 bar text
foo text 3 bar text

Any suggestions or examples on how to do this?

Upvotes: 1

Views: 3222

Answers (5)

glenn jackman
glenn jackman

Reputation: 246799

Assuming you're stuck with that crappy template file:

perl -pe 'BEGIN {$count=0} s/\$variable/ ++$count /ge' file

Upvotes: 1

potong
potong

Reputation: 58391

This might work for you:

printf "foo text %d bar text\n" {1..10}
foo text 1 bar text
foo text 2 bar text
foo text 3 bar text
foo text 4 bar text
foo text 5 bar text
foo text 6 bar text
foo text 7 bar text
foo text 8 bar text
foo text 9 bar text
foo text 10 bar text

or this:

printf "foo text %s bar text\n" foo bar baz
foo text foo bar text
foo text bar bar text
foo text baz bar text 

Upvotes: 1

groovyspaceman
groovyspaceman

Reputation: 2804

It's too trivial a task to write a script for.

Here are a couple of possible solutions:

for (( variable=1; variable<10; ++variable )); do
  echo foo text $variable bar text
done

or...

for name in Dave Susan Peter Paul; do
  echo "Did you know that $name is coming to my party?"
done

Upvotes: 1

sgibb
sgibb

Reputation: 25736

See also http://tldp.org/LDP/abs/html/internalvariables.html#POSPARAMREF:

#!/bin/bash

echo "foo text ${1} bar text"

Upvotes: 1

jordanm
jordanm

Reputation: 34924

This will depend on how you are getting "foo text" and "bar text". If it is set statically:

var="foo text $1 bar text"
echo "$var"

Or if it is in separate variables you can concatenate them:

foo="foo text"
bar="bar text"
output="$foo $1 $bar"
echo "$output"

Upvotes: 0

Related Questions