I have a config file that I want to basically edit the uncommented lines, but not the commented lines. I\'m using sed
.
For example, I have a file calle
To ignore comments that start with a #
when doing a substitution, you can use the following command:
sed -r 'h;s/[^#]*//1;x;s/#.*//;(substitution command);G;s/(.*)\n/\1/' file.txt
In your case it becomes:
sed -r 'h;s/[^#]*//1;x;s/#.*//;s/test/TEST/g;G;s/(.*)\n/\1/' file.txt
The advantage of this solution over the other solutions is that it will also work if there is a comment starting later in a line, as shown in the example below. Since this solution uses the hold buffer of sed, this solution is not possible if you need to use the hold buffer for something else.
test
# test
test # test
test
TEST
# test
TEST # test
TEST
h;
- Save in hold buffers/[^#]*//1;
- Remove everything before #
x;
- Swap with hold buffers/#.*//;
- Remove the comments/test/TEST/g;
- Replace all occurences of test
with TEST
G;
- Append newline + hold buffer (the comment)s/(.*)\n/\1/
- Remove the last newlineThe -r
switch is required for using \1
.