Cut the data with a string that has \ in it

Hi Team,

Here's the record in a file.

abc\USER DEFINED\123\345\adf\aq1

Delimiter here is " \USER DEFINED\ "

Expected output:

abc|123\345\adf\aq1

Find " \USER DEFINED\ " and replace it with " | ".

Can anyone please help us to fix this issue?

Try

echo 'abc\USER DEFINED\123\345\adf\aq1' | sed 's/\\USER DEFINED\\/|/'
abc|123\345\adf\aq1
1 Like

But I need to pass the value during runtime since it changes over a period of time.

Example:

Code:

str1=\\Parallel\\'
sed 's/${str1}/|/g' xyz_file.txt

It did not throw any error message or find and replace it not happening.

Can any one please help me to fix this issue?

Try using double quotes in lieu of single ones.

Try this -

sed 's/'"$str1"'/|/' xyz_file.txt

Expanding a little bit on what RudiC said in post #4 in this thread, shell variable expansions do not occur in single-quoted strings. What chandan.chaman suggested in post #5 would also work, but is more complicated than is needed.

Are backslash characters the only characters that are special in basic regular expressions that might appear in the text you want to replace? (Note that other BRE special characters include the period, opening square bracket (i.e., [ ), asterisk, circumflex, and dollar sign).

Are you creating the search pattern and replacement strings (so you can escape "special" characters)? Or, are they created by users invoking your script?

Does the pattern you want to replace in your file only occur once in your file? Or, can it appear on several lines in your file? Can it ever occur more than once on a single line in your file (and need to have every occurrence replaced)? If the pattern is to be treated as a literal string and doesn't need to be replaced more than once on any line, you might want to use awk 's index () function to find your pattern and use substr () a couple of times to do the replacements instead of using sed 's or ed 's substitute command or awk 's sub () or gsub () function to replace your text.