1

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?

2
  • 1
    It seems to me that there might be a better way to express in code what you are trying to accomplish. It seems a lot of work to type N lines of calls to a script just to create N lines of text. If that's all you want to do, your my_script can just do something like cat >>output.file "foo text $1 bar text". Or can you better describe what you may really want(?) Commented Mar 2, 2012 at 18:12
  • Could this be a possible solution? for i in {1..3}; do echo foo text $i bar text; done Commented Mar 2, 2012 at 18:31

5 Answers 5

1

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

#!/bin/bash

echo "foo text ${1} bar text"
Sign up to request clarification or add additional context in comments.

1 Comment

@jordanm You are right. It is not necessary. But I try to accustom myself to use ${VARIABLENAME} always. IMHO it improves readability and prevent hard-to-find errors.
1

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

Comments

1

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 

Comments

1

Assuming you're stuck with that crappy template file:

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

1 Comment

Excellent, exactly what I was looking for :D
0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.