1

Read a file and comment a line with matching a string via shell script

I want to comment a matching line of file (final_ip) via shell script

I have a input file (input_ip) if the searching ip is matching on final_ip file, change the file content mentioned below

Before changing :

192.168.1.12 #SAM

After the change, the matching line must be replacing :

# 192.168.1.12 #SAM
1
  • If one of the answers has solved the problem, please mark it as accepted using the checkmark. Thank you! Commented Oct 30, 2015 at 15:35

2 Answers 2

2
sed '/<string>/s/^/<comment_char>/' <file>

/<string>/ operates on the lines matching <string>. ^ operates on the beginning of the line and inserts the comment character.

As I understand you you want to read the IP address from a file. Then you can use the following script. Usage: script <file_containing_the_IP_address> <file_to_operate_on>

#!/bin/sh

ip_file="$1"
file_to_change="$2"
comment='# '

ip=$(sed 's/\./\\./g' "$ip_file")
temp_file=$(mktemp)

sed "/$ip/s/^/$comment/" "$file_to_change" > "$temp_file" &&
    mv -- "$temp_file" "$file_to_change"

exit 0

If the script doesn't need to be portable you can also use GNU sed's -i switch.

1
  • Thank you for your support. This is working only if enter it to directly on shell, Is not working on my script, please help. Commented Oct 29, 2015 at 13:37
0

This uses GNU sed's -i extension to edit the final_ip file in-place:

input=`cat input_ip`
sed -i "s/$input/# $input/" final_ip

Putting double-quotes around sed's script allows for the $input variable to be interpolated. Only works if there's one IP in the input_ip file.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.