简体   繁体   English

尝试使用 sed 命令将此 var 包含在 test.txt 文件中以删除双引号

[英]Attempting to include this var in the test.txt file using sed command to remove double quotes

I'm attempting to include this var in the test.txt file using sed command.我正在尝试使用sed命令将此var包含在test.txt文件中。

Tried below script:尝试了以下脚本:

#!/bin/bash
var="test 'test:test:1.0'"
sudo sed -i '/dependencies {/a '"${var}"'' test.txt

test.txt测试.txt

  dependencies {        
        implementation 'org.springframework.boot:spring-boot-starter-web'
        implementation 'org.springframework.boot:spring-boot-starter-cache'        
    }
}

group = 'org.gradle'

I'm using sed to do it, and it's updating the test.txt file, but it's adding with double quotes,我正在使用sed来做它,它正在更新test.txt文件,但它添加了双引号,

Current script result:当前脚本结果:

dependencies {
"test 'test:test:1.0'"
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-cache'        
    }
}

group = 'org.gradle'

and if i remove the double quotes from the variable or sed command results in an error.如果我从变量或sed命令中删除双引号会导致错误。

Error错误

sed: can't read 'ch.qos.logback:logback-classic:1.2.2'": No such file or directory

How can I ignore this double quotes?我怎么能忽略这个双引号?

If I use OP's var assignment ...如果我使用 OP 的var赋值...

var="test 'test:test:1.0'"

... then OP's sed generates: ...然后 OP 的sed生成:

  dependencies {
test 'test:test:1.0'
        implementation 'org.springframework.boot:spring-boot-starter-web'
        implementation 'org.springframework.boot:spring-boot-starter-cache'
    }
}

In other words, I'm unable to reproduce the issue.换句话说,我无法重现该问题。

On the other hand if, as KamilCuk's surmised, var contains double quotes, eg:另一方面,如果正如 KamilCuk 所推测的那样, var包含双引号,例如:

var="\"test 'test:test:1.0'\""

... then I can duplicate OP's output. ...然后我可以复制OP的输出。

So, assuming the double quotes are actually part of what's assigned to var , one idea is to use paramater substitution, eg:因此,假设双引号实际上是分配给var ,一个想法是使用参数替换,例如:

var="\"test 'test:test:1.0'\""
sed "/dependencies {/a ${var//\"/}" test.txt

NOTE: once OP is satisfied with the results the -i flag can be added back into the sed call注意:一旦 OP 对结果感到满意,可以将-i标志重新添加到sed调用中

This generates:这会产生:

  dependencies {
test 'test:test:1.0'
        implementation 'org.springframework.boot:spring-boot-starter-web'
        implementation 'org.springframework.boot:spring-boot-starter-cache'
    }
}

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

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