Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove backslashes with sed command in a file

Tags:

linux

sed

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\\'
...
like image 675
1pa Avatar asked Oct 28 '25 05:10

1pa


2 Answers

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
like image 199
Jim U Avatar answered Oct 29 '25 21:10

Jim U


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\\'
like image 44
Ed Morton Avatar answered Oct 29 '25 22:10

Ed Morton