如何读取用户的输入并使用shell脚本中的输入文本替换.txt文件中的文本?

时间:2016-02-28 16:15:24

标签: shell ubuntu

我正在尝试读取用户的输入并通过替换单词来更新.txt文件。 有没有可能这样做?如果有请帮助我。我希望在 Ubuntu OS 上使用 SHELL 脚本完成此操作。

示例:

我想用以下.Txt文件替换“ Kid ”一词,用户输入“男孩”。

.Txt文件内容:

I love that kid that they are playing on the ground.

一步一步:

  1. 启动Shell计划。
  2. 从用户收到输入$ a。
  3. 阅读.txt文件,找到“ Kid ”一词。
  4. 使用用户输入$ a。
  5. 替换.txt文件中的“Kid”字

    这就是我想做的一切。

1 个答案:

答案 0 :(得分:1)

你的意思是这样的吗?

#!/bin/bash

WORD="foo" # what to find
TXT_FILE="/tmp/lala.txt" # where

# get the new word from user
read -p "With what \"$WORD\" should be replaced ? " newword

# replace, preserving capitalization
output=$(cat "$TXT_FILE" | sed "s/${WORD^}/${newword^}/g" | sed "s/$WORD/$newword/ig")
echo "$output" > "$TXT_FILE"
echo "done"

如果你运行它,你会得到:

/tmp » cat lala.txt 
Foo is riding a bike, while Frank is sunbathing. 
Suddenly, Foo falls. And also Foo, foo, foo.

/tmp » ./lala.sh     
With what "foo" should be replaced ? bar
done

/tmp » cat lala.txt 
Bar is riding a bike, while Frank is sunbathing. 
Suddenly, Bar falls. And also Bar, bar, bar.