加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 在文件中查找一行并在bash中添加一行到行尾

发布时间:2020-12-14 01:23:12 所属栏目:Linux 来源:网络整理
导读:如何识别具有特殊模式的行开头并在行尾添加一些内容? 如果尚未附加应添加的模式 假设我想通过开头的模式在主机文件中找到一个特定的行,可能是ip-address,也可能是行上方的注释 一个例子可能是: #This is your hosts file127.0.0.1 localhost linux #This i
如何识别具有特殊模式的行开头并在行尾添加一些内容?

如果尚未附加应添加的模式

假设我想通过开头的模式在主机文件中找到一个特定的行,可能是ip-address,也可能是行上方的注释

一个例子可能是:

#This is your hosts file

127.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 file

127.0.0.1 localhost linux 
[root@yourserver ~]#

bash脚本:

[root@yourserver ~]# cat so.sh 
#!/bin/bash

_IP_TO_FIND="$1"

# 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 automaticallynn192.168.1.2 domain1. com" text.log
else
  # else insert it directly 
  sed -i .bak "${_LINE_TO_EDIT}i#This is added automaticallynn192.168.1.2 domain1. com" text.log
fi

用法:

bash ./so.sh 127.0.0.1

只需输入您要查找的IP地址,此脚本在第一次出现时就匹配.

希望这可以帮助!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读