1

Let's say I have file:

% This is first line
% This is second line

This is content

% This is the end

How can I insert a % character at the beginning of every line which already starts with %?

Result:

%% This is first line
%% This is second line

This is content

%% This is the end
ilkkachu
  • 138,973
  • this was tagged with [bash] and [sed], so I assume you're not limited to using just plain Bash by itself.. – ilkkachu May 21 '18 at 09:52

2 Answers2

3

With sed

sed 's/^%/%%/' infile

replace beginning % with %% for the lines if starts with.
The ^ is an anchor which points to the beginning of the line; there is $ which points to the end of line.
to have change write to file in-place, use -i option of sed.

There is another way which will do replace faster than above (if your file is huge enough you will notice the difference)

sed '/^%/ s/^/%/' infile
αғsнιη
  • 41,407
0

This can be obtained with sed and awk (though there are other ways as well)

  1. Using sed:
    sed -i 's/^%/%&/' <your_file>
  2. Using awk:
    awk '/^%/ { $0 = "%" $0 } 1' <your_file>