如何在 for 循环中使用字符串?

问题描述 投票:0回答:5

我收到的作业尚未完全包含在学习材料中(即使是指派帮助学生的人也很难帮助我),因为这超出了基本的 bash 脚本编写范围。我不期望任何人完成我的作业,但如果我能得到线索或想法,那将非常有帮助!

我的任务:

在 bash linux 中编写一个脚本,该脚本将使用用户输入的行数和列数,并根据用户的输入打印“hello”,如下所示:

例如:
用户输入的列数:2
用户输入的行数:3

hello hello
hello hello
hello hello

我朝这个方向思考,但我无法弄清楚,并且会感谢任何帮助

echo -e 'Please enter number of rows: \n'
read rows
echo -e 'Please enter number of columns: \n'
read columns

string='hello'
for i in $columns
do
    echo $string
    string+=$string
done

这是我在第一个循环中所得到的,因为我在这里所做的不起作用。

linux bash shell
5个回答
2
投票

看看这个:

#!/bin/bash

read -p 'Please enter number of rows and columns: ' rows columns # prompt and read both vars at once
string='hello' # set string

printf -v row "%${columns}s" # create   var $row consists on N(columns) spaces
row=${row//' '/"$string "}   # recreate var $row changing spaces to "$string "

printf -v col "%${rows}s"    # create var $col consists on N(rows) spaces
all=${col//' '/"$row\n"}     # create full set in var $all by changing spaces to "$row\n"

printf "$all" # print all

测试:

$ ./ex
Please enter number of rows and columns: 3 5
hello hello hello hello hello 
hello hello hello hello hello 
hello hello hello hello hello 

0
投票

有两个循环:

#!/bin/bash

string='hello'
read -p "x:" x
read -p "y:" y

for ((j=0; j<$y; j++)); do
  for ((i=0; i<$x; i++)); do
    echo -n "$space$string"
    space=" "
  done
  space=""
  echo
done

参见:

man bash


0
投票

要读取输入,您可以使用内置的

read
。例如

read -r row column
  • 然后您可以使用

    $row
    $column
    变量。

  • 您需要一个嵌套的

    for
    循环来打印
    row
    x
    column
    次。

  • 要不打印换行符,请使用

    -n
    echo
    选项。

详情请参阅

help read
help for
help echo
。显然你也可以谷歌这些术语;-)


0
投票

你想打高尔夫球吗? :)

printf "%$((rows*columns))s" | fold -w "$columns" | sed 's/ /hello /g'

要提示用户输入

rows
colums
,请使用
read
内置函数:

read -p 'Enter rows: ' rows
read -p 'Enter columns: ' columns

0
投票

我更喜欢在命令行上获取我的参数。
因此,一种实现(没有错误检查......):

rows=$1                        # first arg is rows to output
cols=$2                        # second column is columns wanted
str=$3                         # third arg is the string to print

while (( rows-- ))             # post-decrement rows 
do c=$cols                     # reset a column count for each new row
   while (( c-- ))             # post-decrement columns done
   do printf "%s " "$str"      # print the string with a trailing space, NO newline
   done
   printf "\n"                 # print a newline at the end of each row
done

确保您了解

((
...
))
算术处理、
printf
和命令行参数解析。所有这些都可以在文档中找到。

为了获得额外的积分,请对您的输入进行适当的错误检查。

如果您需要从标准输入而不是命令行读取输入,请替换

rows=$1                        # first arg is rows to output
cols=$2                        # second column is columns wanted
str=$3                         # third arg is the string to print

read rows cols str

更好的是,按照适当的提示阅读每一篇 - 再次强调,详细信息可在手册中找到。

祝你好运。

© www.soinside.com 2019 - 2024. All rights reserved.