0

There is \n string in my file.

Contents of the file source.txt is only one row with text (plus enter at end of first line):

I want to replace only substring \nconsisting of characters \\ and n

You can see \n substring inside before "consisting" word. I want to replace this substring with substring \n and some ident spaces. My script is in file script.sh:

#!/bin/bash

ident="         "
rep_old="\n"
rep_new="\n$ident"

FILE=source.txt
while read line
do
  echo -e "$line"
  echo -e "NEW: ${line//$rep_old/$rep_new}"
done < $FILE

Actual output after call script.sh from bash (my os is Windows):

I want to replace only substring nconsisting of characters \ and n
NEW: I wa
         t to replace o
         ly substri
         g
         co
         sisti
         g of characters \ a
         d

But I want to replace only one \n. I tried also use rep_old="\\n" but without success. What is correct way to achieve this two variants of result?

1: I want to replace only substring \n consisting of characters \\ and n

2: I want to replace only substring consisting of characters \\ and n

What I try based to yours answers:

A: rep_old="\\\\n"

A: result:

I want to replace only substring nconsisting of characters \ and n
NEW: I want to replace only substring nconsisting of characters \ and n
Atiris
  • 2,613
  • 2
  • 28
  • 42

1 Answers1

1

This is to do with 'double escaping', happening at variable set time AND at use time consider this:

$ echo "\\n"
\n

$ x="\\n"
$ echo $x
\n

so even if I escape n with \\ on creation on use its \n

try:

$ rep_old="\\\\n"

which gives

$ echo $rep_old
\\n

UPDATED Sorry you have a second problem, which is:

while read line <-- this is already eating the \n as it is reading that as an escape
do
  echo -e "$line"

see this: sh read command eats slashes in input?

try this:

while read -r line

giving:

I want to replace only substring
consisting of characters \ and n
NEW: I want to replace only substring
         consisting of characters \ and n
Community
  • 1
  • 1
tolanj
  • 3,651
  • 16
  • 30