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

问题描述

我很抱歉我的问题不够具体,但我别无选择。所以我收到了一份学习材料中没有完全涵盖的作业(即使是被指派帮助学生的人也无法帮助我),因为这超出了基本的 bash 脚本编写。我不指望任何人来完成我的任务,但如果我能得到线索或想法,那将非常有帮助!

我的任务:

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

例如:
用户输入的列数: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

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

解决方法

看看这个:

#!/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 
,

要读取输入,您可以使用内置的 read。例如

read -r row column
  • 然后您可以使用 $row$column 变量。

  • 您需要一个嵌套的 for 循环来打印 row x column 次。

  • 要不打印换行符,请使用 -necho 选项。

有关详细信息,请参阅 help readhelp forhelp echo。显然,您也可以使用 Google 搜索这些术语 ;-)

,

有两个循环:

#!/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

,

你想打高尔夫球吗? :)

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

要提示用户输入 rowscolums,请使用内置的 read

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

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

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 和命令行参数解析。所有这些都可以在 documentation 中找到。

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

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

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

最好用适当的提示阅读每一个 - 同样,手册中提供了详细信息。

祝你好运。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...