简体   繁体   中英

linux bash sed-command with variable

I have a variable in a linux bash ".sh" script

$data="test_1"

now I want to create a new variable ($name) that contains only the part of $data before the underscore, so

$name="test"

I thought of doing this with sed

name=$(echo "$dataset" | sed 's/_.*//');

but this doesn't seem to work. What am I doing wrong?

No need to call an external process( sed ). Instead you can use shell's parameter substitution like this:

$ data="test_1"

$ echo "${data%%_*}"
test

${var%%Pattern} Remove from $var the longest part of Pattern that matches the back end(from the right) of $var .

${var%Pattern} for removing shortest pattern

More info on parameter substitution can be found here .

You can store it in a variable like this:

$ name="${data%%_*}"

$ echo "$name"
test

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