1pa
1pa

Reputation: 735

Remove backslashes with sed command in a file

I have a file like this:

'AAA' 'a\\\\b\\\\a\\'
'BBB' 'q\\l\\s\\'
...

And I want to replace all occurrences of \\\\ with \\.

I tried this sed command:

sed 's/\\//g'

but this removes all \.

This is my output:

'AAA' 'aba'
'BBB' 'qls'

The output I want:

'AAA' 'a\\b\\a\\'
'BBB' 'q\\l\\s\\'
...

Upvotes: 3

Views: 4388

Answers (3)

Jim U
Jim U

Reputation: 3366

Replaces sequences of 4 backslashes with 2 backslashes:

sed 's/\\\\\\\\/\\\\/g' input.txt

Alternatively, use {4} to indicate how many \ are matched:

sed 's/\\\{4\}/\\\\/g' input.txt

input.txt

'AAA' 'a\\\\b\\\\a\\'
'BBB' 'q\\l\\s\\'

output

'AAA' 'a\\b\\a\\'
'BBB' 'q\\l\\s\\'

You must escape special regex characters like \ with another \.

{ and } are also regex characters, however the ed-like tools (ed,vim,sed,...) don't recognize them as such by default. To use curly-braces to specify a regex count (e.g., {4}), sed requires you escape them (e.g., \{4\})

So...

  • escape \ to use it literally; not as a regex character
  • escape { and } to use them as regex characters rather than literal braces

Upvotes: 3

Ed Morton
Ed Morton

Reputation: 203502

With any sed that supports EREs, e.g. GNU or AIX seds:

$ sed -E 's/(\\){4}/\\\\/' file
'AAA' 'a\\b\\\\a\\'
'BBB' 'q\\l\\s\\'

Upvotes: 3

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

I want to replace all '\\\\' to '\\'

Use the following approach:

sed 's/\\\\\\\\/\\\\/g' file

The output:

'AAA' 'a\\b\\a\\'
'BBB' 'q\\l\\s\\'

each backslash \ should be escaped with ... backslash :)

Upvotes: 1

Related Questions