如何使用shell脚本搜索和替换文件内容?
几天前我开始学习shell脚本。我的情况是,我必须使用 shell 脚本搜索并替换文件中不同行中存在的内容。
例如,我在文件中提到了路径名:-
path = /home/test/db
我的名字是这样,
path = /home/test/db
在这里, 必须使用 shell 脚本将文件的指定行中的路径名“/home”替换为“/Second”。通过使用“sed”命令,我尝试并替换了文件的内容只有一行,但我正在努力替换不同行中存在的内容。我在 shell 脚本中使用“If”条件。请帮助我解决这个问题。
谢谢和问候,
I have started learning shell scripting a few days ago. My scenario is, i have to search and replace a content which exists in different lines in a file using shell script.
For Example, I have mentioned the path name in a file :-
path = /home/test/db
My name is so and
path = /home/test/db
Here,
The path name "/home" has to be replaced with "/Second" in specified lines of the file using shell script. By using "sed" command i have tried and replaced the content of the file has only one line but i am struggling with replacing which is present in different lines. I am using "If" condition in shell script.Please do help me in resolving this case.
Thanks and Regards,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信您错过了 sed 命令中的 g 选项。见下文
I believe you missed the g option in your sed command. See below
sed -i 's/original/new/g' file.txt
说明:
sed -i 's/original/new/g' file.txt
Explanation:
下面提到的代码将搜索“search_folder_name”下的所有JS文件。它将在定义的文件夹中查找所有出现的“version_number”,并将其替换为定义的相应值。将下面提到的代码保存在 .sh 文件中,例如 test.sh
The below mentioned code will search all JS files under "search_folder_name". It will find "version_number" for all occurrences in the defined folder and replace it with respective value defined. Save the below menioned code in .sh file say, test.sh