Replace odd and even occurrences of a pattern to another same pattern Replace odd and even occurrences of a pattern to another same pattern unix unix

Replace odd and even occurrences of a pattern to another same pattern


Another sed solution:

$ cat ip.txt\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\$ sed -E 's/(\\+)\1\\?/\1/g' ip.txt\\\\\\\\\\\\\\\\\

(\\+)\1\\? will evenly divide the backslashes, the optional matching at the end will consume the last backslash for odd cases.

If single backslash should be removed instead of being preserved, use

sed -E 's/((\\+)\2)?\\?/\2/g'


You may try this awk:

cat file\\\\\\\\\\\\\\\\\\\\\\\\\\\\\# using awkawk '{print substr($0, 1, int(length($0)/2))}' file\\\\\\\\\\\\\\


Using sed: in lines with an odd number of \ first get rid of the last one. Then substitute pairs, as you did:

sed -r 's/((\\\\)*)(\\)?/\1/g;s/\\\\/\\/g'

Demo:

$ cat foo.txt\\\\\\\\\$ sed -r 's/((\\\\)*)(\\)?/\1/g;s/\\\\/\\/g' foo.txt\\\\