Reputation: 31
I'm trying to look for a substring --port 1234
in a file and if the line is not commented then, comment out the line with #
and insert a new line underneath it defined as this is the new path: /new/path/to/file
. If the line containing --port 1234
is already commented, then do nothing. If substring --port 1234
is not found in the file then echo "not found"
Sample input:
somecode somecode
somecode somecode --port 1234 somecode somecode somecode
somecode somecode
Sample output:
somecode somecode
#somecode somecode --port 1234 somecode somecode somecode
This is the new path: /new/path/to/file
somecode somecode
Here's what I have so far:
sed -E '/--port 1234/!b;/^[^#]/!b;
so far I've only figured out how to ignore if the line is already commented, or if a line does not contain --port 1234
. Very new to bash script!
Upvotes: 2
Views: 57
Reputation: 35146
Sticking with the sed
idea:
Sample input, with and without leading comment (#
):
$ cat myfile
somecode somecode
somecode somecode --port 1234 somecode somecode somecode
somecode somecode
#somecode somecode --port 1234 somecode somecode somecode
somecode somecode
One sed
idea:
$ sed -E 's|^([^#].*--port 1234.*)$|#\1\nThis the new path: /new/path/to/file|' myfile
somecode somecode
#somecode somecode --port 1234 somecode somecode somecode
This the new path: /new/path/to/file
somecode somecode
#somecode somecode --port 1234 somecode somecode somecode
somecode somecode
Once OP is satisfied with the result the -i
flag can be added to perform an inplace update of the file.
Upvotes: 0
Reputation: 785721
awk
is more suitable for this job.
Sample File:
cat file
foo bar
#somecode somecode --port 1234 somecode somecode somecode
somecode somecode
somecode somecode --port 1234 somecode somecode somecode
somecode somecode
Use gnu awk
as:
awk -i inplace '/--port 1234 / && !/^#/ {
print "#" $0 ORS "This is the new path: /new/path/to/file"
next
} 1' file
foo bar
#somecode somecode --port 1234 somecode somecode somecode
somecode somecode
#somecode somecode --port 1234 somecode somecode somecode
This is the new path: /new/path/to/file
somecode somecode
Upvotes: 1