Find the line in the file and add something to the end of the line in bash

How can I identify the beginning of a line with a special pattern and add something to the end of the line?

if the template to be added is not yet added

Suppose I would like to find a specific line in the host file, either by the template at the beginning it can be an IP address, or a comment above the line

An example would be:

#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

How to tell bash when you find the IP address that I will tell you. go ro lines end and add something

or in another case

When bash finds a comment #This is added automatically

go down to 2 and then go to the end of the line and add something

You see that I am new and have no idea what to use here and how. Is this done by sed? or can this be done with grep? Should I learn AWK for this?

+4
3

:

Textfile:

[root@yourserver ~]# cat text.log 
#This is your hosts file

127.0.0.1 localhost linux 
[root@yourserver ~]# 

bash script:

[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-, , script .

, !

+3

"127.0.0.1".

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

​​ , 127.0.0.1 sed:

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
+5

sed :

sed -i.bak 's/^192\.168\.1\.2.*$/& ADDED/' hosts 
  • sed , 192.168.1.2
  • , ADDED
+1

Source: https://habr.com/ru/post/1502854/


All Articles