Issue
I have a huge file containing datasets such as:
100 S|||
100 S|d1|||88|||
100 S|0d|f6||f630|589f||
I need to replace |||
with |||||||
, only if the line contains no more pipes other than a single |||
sequence.
I tried using sed command for this requirement:
sed -i 's/|||/|||||||/g' input.txt
However, it is changing records in second line as well, which is not intended.
What would be the correct command usage? Any help will be highly appreciated.
Solution
You can use this sed
command with capture groups to match non-pi[e characters before and after |||
:
sed -E 's/^([^|]*)(\|\|\|)([^|]*)$/\1\2||||\3/' file
100 S|||||||
100 S|d1|||88|||
100 S|0d|f6||f630|589f||
Details:
^
: Start([^|]*)
: Match 0 or more non-pipe characters in capture group #1(\|\|\|)
: Match 3 pipe characters in capture group #2([^|]*)
: Match 0 or more non-pipe characters in capture group #3$
: End\1\2||||\3
is replacement pattern that inserts||||
after back-reference #2 i.e.\2
while putting back\1
and\3
as is.
Answered By - anubhava Answer Checked By - Katrina (WPSolving Volunteer)