I have a file like this:1,2,subjects,\mat\hs,unix\,\Nato,\N,123,\NI want to replace all occurences of \ with #, except for \N, such that the output looks like this:1,2,subjects,#mat#hs,unix#,#Nato,\N,123,\NI am trying to write a sed command which looks like-sed -e 's@\\([^N])@#\1/g' filenamebut this will fail for all values wherever there is a \N at the start for ex. \Nato in above example.Could somebody please help me figure out a sed command(regex) for my requirement.
Replace all occurences of \ except \N
sed;regular expression
I'm not that well-versed in sed. But this can be done easily in perl using regex lookaround:perl -pe 's/\\(?!N\b)/#/g' your_file_hereThis will print the modified file to stdout. To make the substitutions in place, you can do:perl -pi -e 's/\\(?!N\b)/#/g' your_file_hereBasically, this substitutes any backslash not followed by N\b (the character N at a word boundary) with #.EditIf you're absolutely sure that your entries are comma-delimited, you can do this to cover the case when \N is at the end of a word (as in SOLEM\N in the example you supplied):perl -pe ' s/\\/#/g; s/(\A|,)\s*#N\s*(\Z|,)/$1\\N$2/g;' your_file_hereIt simply substitutes any backslash with a hash mark then looks for #N found between two commas, between the beginning of the string and a comma or between a comma and the end of the string.