bash - 创建一个从控制台读取变量的脚本,并将这些值替换为用大括号括起来的值
问题描述
我有一个小任务,这是我坚持的部分。我得到了一个文本,文本中有类似的字符串:{形容词}、{名词}等。我的脚本应该允许用户在控制台中编写他/她想要的任何内容,我将在文本中替换这些单词。
到目前为止,我的方法是创建一个 for 循环遍历每一行并以某种方式使用sed但我不知道如何。非常感谢任何提示或帮助。事先谢谢你。
编辑:到目前为止,我的代码能够替换形容词,我想不出一种方法来使用if 语句来做其他事情。很抱歉对这个网站缺乏了解。
i=1
while [ $i -le 20 ]
do
echo Please enter an adjective :
read var
sed -i "s/{adjective}/$var/g" file.txt
i=$((i + 1))
done
cat file.txt
这是一个示例 file.txt 文件:
The {adjective} fox jumped over the lazy {animal}.
这是一个示例运行:
Please enter a(n) adjective: quick
Please enter a(n) animal: dog
这是预期的结果。
$ cat file.txt
The quick fox jumped over the lazy dog.
解决方案
这是一个可能对您有用的解决方案:
file=$1
for variable in $( grep -o '{[^}]*}' $file )
do
read -p "Please enter a(n) $variable: " var
sed -i.bk -e "s/$variable/$var/" $file
done
这是一个示例调用:
$ cat file.txt
The {adjective} fox jumped over the lazy {animal}.
$ ./madlibs.sh file.txt
Please enter a(n) {adjective}: quick
Please enter a(n) {animal}: dog
$ cat file.txt
The quick fox jumped over the lazy dog.
推荐阅读
- html - xslfo, xsl, pdf, html: 在某些页面之后为动态生成的 pdf 文档重置页脚页码
- java - MP4 视频的文件输入/输出流
- django - 在 django-rest-framework 中发送电子邮件的最佳位置在哪里?
- php - 尝试使用 isset 设置值但仍然出现错误
- python - 合并并创建一个包含相同 id 的所有记录的新 JSON 数组
- ms-access - 在 MS Access 2016 中向现有查询(不是表)添加自动增量
- java - stringbuffer 在连接中比 string 快我可以知道它们是如何实现的吗
- python - 如何在没有 tkinter 使小部件居中的情况下向 tkinter 窗口添加填充?
- python - QTableView 选择更改
- xml - 如何使用 Jackson XmlMapper 控制编码?