簡體   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