简体   繁体   中英

Find line containing string and replace another string with new string

I have a file with multiple lines that contain ip addresses and a varaible afterwards .....

example

server 127.0.0.1:80    VARTOREPLACE
server 127.1.0.1:80    VARTOREPLACE
server 127.2.0.1:80    VARTOREPLACE

How could I go about scanning through the file and matching an ip pattern then setting that var which matches in that line to a particular string..... example

  • if ip matches 127.*.*.* replace VARTOREPLACE with NEWVAR1
  • if ip matches 127.1.*.* replace VARTOREPLACE with NEWVAR2
  • if ip matches 127.2.*.* replace VARTOREPLACE with NEWVAR3

I've tried

sed -i '/:127.0 /s/VARTOREPLACE/NEWVAR1/' file

Any help would be appreciated.

Try below command -

sed '/127.0.0/s/VARTOREPLACE/NEWVAR1/g;/127.1.0/s/VARTOREPLACE/NEWVAR2/g;/127.2.0/s/VARTOREPLACE/NEWVAR3/g'
server 127.0.0.1:80    NEWVAR1
server 127.1.0.1:80    NEWVAR2
server 127.2.0.1:80    NEWVAR3

Try this simple command:

sed -i -e '/127.0/s/VARTOREPLACE/NEWVAR1/' file -e '/127.1/s/VARTOREPLACE/NEWVAR2/' file

Although I wouldn't recommend it if there are many other variables. You should have another file that does a sort of vlookup for you

@Eric Cox: Try an awk solution too.

awk '$2 ~ /127.1.[0-9]+.[0-9]+/{$NF="NEWVAR2";print;next} $2 ~ /127.2.[0-9]+.[0-9]+/{$NF="NEWVAR3";print;next} $2 ~ /127.[0-9]+.[0-9]+.[0-9]+/{$NF="NEWVAR1";print;next}1'  Input_file

Checking if field 2nd is equal to any of the ranges provide by you into your post(changing the * with [0-9] as * may contain characters etc too), then if condition is TRUE with respect to $2 then changing the $NF(last field) with value of "NEWVAR1" etc then printing the newly formatted line and putting next statement to skip all further statements. At last mentioning 1 to print the lines if none of the conditions matched then it will simply print the line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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