
如果尚未附加应添加的模式
假设我想通过开头的模式在主机文件中找到一个特定的行,可能是ip-address,也可能是行上方的注释
一个例子可能是:
#This is your hosts file127.0.0.1 localhost linux #This is added automatically 192.168.1.2 domain1. com #this is added automatically to 192.168.1.2 sub.domain1.com www.domain1.com
当你找到我告诉你的IP时,我如何告诉bash.去结束并添加一些东西
或其他情况
当bash发现评论时#This会自动添加
往下走2,然后到最后一行添加一些东西
你看我是初学者,并且没有任何想法在这里使用什么以及如何使用.是由sed解决?或者这可以用grep完成吗?我必须学习AWK吗?
解决方法 鉴于以下内容:文本文件:
[root@yourserver ~]# cat text.log #This is your hosts file127.0.0.1 localhost linux [root@yourserver ~]#
bash脚本:
[root@yourserver ~]# cat so.sh #!/bin/bash_IP_TO_FIND=""# sysadmin 101 - the sed command below will backup the file just in case you need to revert_BEST_PATH_liNE_NUMBER=$(grep -n "${_IP_TO_FIND}" text.log | head -1 | cut -d: -f1)_liNE_TO_EDIT=$(($_BEST_PATH_liNE_NUMBER+2))_TOTAL_lines=$( wc -l text.log)if [[ $_liNE_TO_EDIT -gte $_TOTAL_lines ]]; then # if the line we want to add this to is greater than the size of the file,append it sed -i .bak "a${_liNE_TO_EDIT}i#This is added automatically\n\n192.168.1.2 domain1. com" text.logelse # else insert it directly sed -i .bak "${_liNE_TO_EDIT}i\#This is added automatically\n\n192.168.1.2 domain1. com" text.logfi 用法:
bash ./so.sh 127.0.0.1
只需输入您要查找的IP地址,此脚本在第一次出现时就匹配.
希望这可以帮助!
总结以上是内存溢出为你收集整理的linux – 在文件中查找一行并在bash中添加一行到行尾全部内容,希望文章能够帮你解决linux – 在文件中查找一行并在bash中添加一行到行尾所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)