繁体   English   中英

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

[英]Find a line in a file and add something to the end of the line in bash

如何识别具有特殊模式的行开头并在行尾添加一些内容?

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

假设我想通过开头的模式在主机文件中找到一个特定的行,可能是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 is added automatically

往下走2,然后到最后一行添加一些东西

你看我是初学者,并且没有任何想法在这里使用什么以及如何使用。 是由sed解决? 或者这可以用grep完成吗? 我必须学习AWK吗?

这将在行尾添加一些文本,格式为“127.0.0.1”。

grep -F "127.0.0.1" file | sed -ie 's/$/& ADDing SOME MORE TEXT AT THE END/g'

以下将通过sed添加到以127.0.0.1开头的文件中的行:

sed -ie 's/^127.0.0.1.*$/& ADDing MORE TEXT TO THE END/g' file

要做同样的事情,你也可以使用awk

awk '/^127.0.0.1/{print $0,"ADD MORE TEXT"}' file > newfile && mv newfile file
  • 编辑

如果要通过变量调用IP地址,则语法可能略有不同:

var="127.0.0.1"
grep -F "$var" file | sed -ie 's/$/& ADD MORE TEXT/g'
sed -ie "s/^$var.*$/& ADD MORE TEXT/g" file
awk '/^'$var'/{print $0,"ADD MORE TEXT"}' file > newfile && mv newfile file

鉴于以下内容:

文本文件:

[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地址,此脚本在第一次出现时就匹配。

希望这可以帮助!

这个内联sed应该工作:

sed -i.bak 's/^192\.168\.1\.2.*$/& ADDED/' hosts 
  1. 此sed命令查找以192.168.1.2开头的行
  2. 如果发现它在这些行的末尾添加了ADDED

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM