Issue
I need to replace only single instance of backslash.
Input: \\apple\\\orange\banana\\\\grape\\\\\
Output: \\apple\\\orangebanana\\\\grape\\\\\
Tried using sed 's/\\//g' which is replacing all backslashes
Note: The previous character to single backslash can be anything including alphanumeric or special characters. And it's a multiline text file.
Appreciate your help on this.
Solution
If you want to consider perl
then lookahead and lookahead is exactly what you need here:
perl -pe 's~(?<!\\)\\(?!\\)~~g' file
\\apple\\\orangebanana\\\\grape\\\\\
Details
(?<!\\)
: Negative lookbehind to make sure that previous char is not\
\\
: Match a\
(?!\\)
: Negative lookahead to make sure that next char is not\
If you want to use sed
only then I suggest:
sed -E -e ':a' -e 's~(^|[^\\])\\([^\\]|$)~\1\2~g; ta' g
Answered By - anubhava Answer Checked By - Dawn Plyler (WPSolving Volunteer)