1

I want to write a script which takes two parameters, a string and a number. The script with print the string n time rounded with asterisks. So for ex. script "Hello World!" 3 will print:

**************
*Hello World!*
*Hello World!*
*Hello World!*
**************

How can I do this?

5
  • printf '*HelloWorld*\n%.0s' {1..3} Commented Sep 1, 2016 at 14:24
  • but i can not print the first and last line with asterisks. Also I want to do it with parameters not manually. Commented Sep 1, 2016 at 14:25
  • I take it that you need to do this with a single printf statement? As you could simply just perform a printf '************\n before and after your existing printf, right? Commented Sep 1, 2016 at 14:28
  • I cant to that because length will vary on the string length. and it need to be a script which takes parameters. Commented Sep 1, 2016 at 14:36
  • 1
    echo $1 | sed 's/./*/g' Commented Sep 1, 2016 at 15:04

2 Answers 2

1

We can make a string of * characters the same length as the input with sed. We can also loop pretty simply. The output of each line would then be

*$stars*
*$input*
...repeated...
*$stars*

So we can make a simple "output" function that just puts the * around the required string

#!/bin/bash

string=$1
count=$2

stars=$(echo "$string" | sed 's/./*/g')

output() { printf "*%s*\n" "$1"; }

output "$stars"
for ((a=0;a<$count;a++))
{
  output "$string"
}
output "$stars"

eg

./x "Hello world!" 3
**************
*Hello world!*
*Hello world!*
*Hello world!*
**************
0

One way of doing this is using seq for the number of times the string is echo'd, and printf with string manipulation for the asterisks.

SAY=$1
NUM=$2
CMD="echo *$SAY*"

c="${SAY//[*]}**"
s=$(printf "%-${#c}s" "*")
echo "${s// /*}"

for i in $(seq $NUM)
do $CMD
done

echo "${s// /*}"

You can then use this script with arguments ./script.sh "Hello World" 3

2
  • And the asterisks? Commented Sep 1, 2016 at 14:41
  • Oops, completely missed that! I've edited my answer accordingly. Commented Sep 1, 2016 at 15:10

You must log in to answer this question.