写一个剧本.Eg:
echo "my name is 'read' and am from 'read' city" > outfile.txt
当它运行时,它不会先打印句子,即my name is
。相反,它要求首先输入2个输入,使用2个读取命令,然后形成完整的句子,如"我的名字是 sudhir ,来自 vizag 城市"
我希望脚本执行第一个"我的名字是read(ask for input)
,来自read(ask for another input)
city"在输入后,它应该一次性重定向到outfile.txt。
如何处理?用单句实现是否可行?
因为我想在一个文件中使用480个问题的相同逻辑,而人们如何没有任何脚本知识应该能够参考同一文件中存在的先前问题添加更多问题。
答案 0 :(得分:0)
没有一种漂亮的方法可以做到这一点,因为read
将换行字符从输入写入终端,但我们可以在两次传递中执行此操作。
您可以将以下内容放入脚本
#!/bin/bash
echo -n 'my name is '; read -r name
echo -n ' and I am from '; read -r city
echo ' city'
printf "my name is %s and I am from %s city\n" \
"$name" "$city" > output.txt
对于用户来说,它看起来像这样
my name is sudhir
and I am from vizag
city
但是在文件
中会是这样的my name is sudhir and I am from vizag city
答案 1 :(得分:0)
你可以编写一个带有占位符字符串的函数,并要求用户为每个字符串输入:
#!/bin/bash
fill() {
arg="$*"
result=""
while [[ "$arg" =~ ([^_]*)(_+)(.*) ]]
do
read -rp "${BASH_REMATCH[1]# }${BASH_REMATCH[2]}: " input
result+="${BASH_REMATCH[1]}${input}"
arg="${BASH_REMATCH[3]}"
done
result+="$arg"
printf '%s\n' "$result"
}
exec > outputfile
fill "My name is ____ and I am from ___."
fill "My new years resolution is ____."
示例:
$ ./myscript
My name is ____: Sudhir
and I am from ___: Vizag
My new years resolution is ____: learning Bash instead of asking SO to write my scripts
$ cat outputfile
My name is Sudhir and I am from Vizag.
My new years resolution is learning Bash instead of asking SO to write my scripts.