简体   繁体   中英

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.

Tried below script:

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

test.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,

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.

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 ...

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

... then OP's sed generates:

  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:

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

... then I can duplicate OP's output.

So, assuming the double quotes are actually part of what's assigned to var , one idea is to use paramater substitution, eg:

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

This generates:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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