在文件中查找一行,然后在bash中向该行的末尾添加一些内容 [英] Find a line in a file and add something to the end of the line in bash

查看:145
本文介绍了在文件中查找一行,然后在bash中向该行的末尾添加一些内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何识别以特殊模式开头的行,并在行末添加内容?

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

if the pattern that should be added is not already appended

假设我想通过开头的模式可能是ip地址或该行上方的注释来找到主机文件中的特定行

Let's say I'd like to find a specific line in the host file either by the pattern at the beginning may be an ip-address or by the comment that is above the line

一个例子可能是:

#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.滚到行尾并添加一些东西

How do I tell bash when you find the IP I tell you. go ro the lines end and add something

或其他情况

当bash找到注释#This is added automatically

向下移动2,然后移至行尾并添加一些内容

go down by 2 and than go to the end of the line and add something

您看到我是一个初学者,没有任何想法在这里使用什么以及如何使用.是由sed完成的吗?还是可以用grep做到这一点?我必须为这些东西学习AWK吗?

You see I'm a beginner and don't have any Idea what to use here and how. Is dis done by sed? or could this be done with grep? do I have to learn AWK for that stuff?

推荐答案

给出以下内容:

文本文件:

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

用法:

bash ./so.sh 127.0.0.1

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

Simply enter in the ip address you're trying to find and this script matches on the first occurrence of it.

希望这会有所帮助!

这篇关于在文件中查找一行,然后在bash中向该行的末尾添加一些内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆