Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed paste below pattern string in variable

I am looking for a solution to paste a variable below a matching pattern I have a half solution but cannot finish my script... My aim with this script is to paste the variable "OSI" automatically below the correct Month.

/var/etc/osi.conf
    ###Jan###
    ###Feb###
    ###Mar###
    ###Apr###
    ###May###
    ###Jun###
    ###Jul###
    ###Aug###
    ###Sep###
    ###Oct###
    ###Nov###
    ###Dec###

Script:

    #!/bin/bash +x
    DATE=$(date | awk '{print $2}')
    DATE2=$(date +%Y-%m-%d -d "3 year")
    read -r -p "USERNAME: " USERNAME
    read -r -p "PASSWORD: " PASSWORD


    OSI="
    "$USERNAME"
    "$PASSWORD"
    "$DATE2"
    Fail 1
    eth0"

    sed -i 's/\#\#\#"$(date | awk '{print $2}')"\#\#\#/$OSI/g' /var/etc/osi.conf

///###EDITED###

Below you can find the result. Because the creation month is March and. Hence, the created user must be below ###Mar###

var/etc/osi.conf

###Jan###
###Feb###
###Mar###
"$USERNAME"
"$PASSWORD"
"$DATE2"
Fail 1
eth0"
###Apr###
###May###
###Jun###
###Jul###
###Aug###
###Sep###
###Oct###
###Nov###
###Dec###
like image 398
Goeks Avatar asked Feb 14 '26 21:02

Goeks


1 Answers

I modified, so I don't have to input some name, don't mess around in /etc, don't have issues with locale and date and keep osi.conf unchanged for testing:

DATE=$(LC_ALL=C date | awk '{print $2}')
DATE2=$(LC_ALL=C date +%Y-%m-%d -d "3 year")
USERNAME="Hein"
PASSWORD="53cr3t"

echo -e "$USERNAME\n$PASSWORD\n$DATE2\nFail 1\neth0" > tmp.txt

sed "/$DATE/rtmp.txt" osi.conf

Result:

###Jan###
###Feb###
###Mar###
Hein
53cr3t
2021-03-13
Fail 1
eth0
###Apr###
###May###
###Jun###
###Jul###
###Aug###
###Sep###
###Oct###
###Nov###
###Dec###

If you need quotes around some values, experiment with masking or read the reference.

The keypoint here is sed's ability (Gnu-sed) to r:=read a file and input it at a certain pattern or line number.

like image 87
user unknown Avatar answered Feb 17 '26 11:02

user unknown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!