首页 > 解决方案 > 创建一个从控制台读取变量的脚本,并将这些值替换为用大括号括起来的值

问题描述

我有一个小任务,这是我坚持的部分。我得到了一个文本,文本中有类似的字符串:{形容词}、{名词}等。我的脚本应该允许用户在控制台中编写他/她想要的任何内容,我将在文本中替换这些单词。

到目前为止,我的方法是创建一个 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.

标签: bashshell

解决方案


这是一个可能对您有用的解决方案:

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.

推荐阅读