简体   繁体   English

替换bash脚本中的字符串'\\ n'(不是'行尾')

[英]Replace string '\n' (not 'end of line') in bash script

There is \\n string in my file. 我的文件中有\\n字符串。

Contents of the file source.txt is only one row with text (plus enter at end of first line): 文件source.txt内容只有一行带有文本(在第一行的末尾加回车):

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

You can see \\n substring inside before "consisting" word. 您可以在“由”组成的单词之前看到\\n子字符串。 I want to replace this substring with substring \\n and some ident spaces. 我想将此子字符串替换为子字符串\\n和一些标识空格。 My script is in file script.sh : 我的脚本在文件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): 从bash调用script.sh之后的实际输出(我的操作系统是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 . 但是我只想替换一个\\n I tried also use rep_old="\\\\n" but without success. 我尝试过也使用rep_old="\\\\n"但没有成功。 What is correct way to achieve this two variants of result? 实现这两种结果的正确方法是什么?

1: I want to replace only substring \\n consisting of characters \\\\ and n 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 2: I want to replace only substring consisting of characters \\\\ and n

What I try based to yours answers: 我根据您的回答尝试的方法:

A: rep_old="\\\\\\\\n" 答: 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

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 所以即使我使用 \\ n在创建使用 \\\\转义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? 看到这个: sh read命令在输入中吃斜线?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM