我怎样才能确定一个特殊模式的行开始,并添加到行的末尾?
如果应该添加的模式尚未附加
假设我想在主机文件中find一个特定的行,可以通过开头的模式可以是一个IP地址,也可以通过上面的注释
一个例子可能是:
#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
当我findIP时,如何告诉bash我告诉你。 去结束线添加一些东西
或另一种情况
当bash发现注释#This is added automatically
往下走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 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地址,并且此脚本首次匹配。
希望这可以帮助!
这将使用模式“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
这个内联sed应该工作:
sed -i.bak 's/^192\.168\.1\.2.*$/& ADDED/' hosts
192.168.1.2
开头的行 ADDED