我正在尝试读取用户的输入并通过替换单词来更新.txt文件。 有没有可能这样做?如果有请帮助我。我希望在 Ubuntu OS 上使用 SHELL 脚本完成此操作。
示例:
我想用以下.Txt文件替换“ Kid ”一词,用户输入“男孩”。
.Txt文件内容:
I love that kid that they are playing on the ground.
一步一步:
这就是我想做的一切。
答案 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.