简体   繁体   中英

writing a bash script that deletes a variable in another file

OK so I asked the question how to add a variable to the end of a line in another file last night and got GREAT answers, thanks for that by the way! Now I want to do the reverse.
I am writing a bash script that basically undoes what I did with the first. As part of that I have the same variable and now I want to remove it from another file, this time it could be anywhere in that file and I just want to remove it without changing the file or breaking the line it is in. Not even sure where to start on this one but. Say I have

echo -e "Enter inside IP address to be Removed: \c"
read inside_ip

now I need a command that removes $inside_ip from file list-of-ips which is a single line of IPs like

1.1.1.1 2.2.2.2 3.3.3.3 ...

A bit unclear but this should get you started:

$ cat input
1.1.1
2.2.2
3.3.3
4.4.4
5.5.5

$ ip='3.3.3'

$ sed "/$ip/d" input
1.1.1
2.2.2
4.4.4
5.5.5

Note the " quotation in the sed command above, " allow the shell to perform parameter expansion, if you instead used single-quotes ' , sed would look for the literal string $ip and you don't want that.

Use sed -i to make the changes inline

As fredrik mentioned, use of sed will work but I would use the following since your results are all on one line...

Suppose file foo.txt contains the following:

1.1.1.1 2.2.2.2 3.3.3.3 4.4.4.4

You could use the following to remove your ip:

ip="3.3.3.3"
sed -i 's/\b'$ip'\b//g' foo.txt

Results would be:

1.1.1.1 2.2.2.2  4.4.4.4

This will remove the matches globally within the line (in case you have multiple matches). Also keep in mind that the dots in the ip address mean any character match in regex so there is the small potential to have an unexpected match. You can place backslashes in your ip variable to avoid it if needed.

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