简体   繁体   English

使用grep分割字符串的Shell脚本

[英]Shell scripting using grep to split a string

I have a variable in my shell script of the form 我在表单的shell脚本中有一个变量

myVAR = "firstWord###secondWord"

I would like to use grep or some other tool to separate into two variables such that the final result is: 我想使用grep或其他工具分成两个变量,最终结果如下:

myFIRST = "firstWord"
mySECOND = "secondWord"

How can I go about doing this? 我该怎么做呢? #{3} is what I want to split on. #{3}是我想分开的。

Using substitution with sed : 使用sed替换:

echo $myvar | sed -E  's/(.*)#{3}(.*)/\1/'
>>> firstword

echo $myvar | sed -E  's/(.*)#{3}(.*)/\2/'
>>> secondword

# saving to variables
myFirst=$(echo $myvar | sed -E  's/(.*)#{3}(.*)/\1/')

mySecond=$(echo $myvar | sed -E  's/(.*)#{3}(.*)/\2/')

The best tool for this is : 最好的工具是

$ echo "firstWord###secondWord" | sed 's@###@\
@'
firstWord
secondWord

A complete example : 一个完整的例子:

$ read myFIRST mySECOND < <(echo "$myvar" | sed 's@###@ @')

$ echo $myFIRST 
firstWord

$ echo $mySECOND 
secondWord
$ STR='firstWord###secondWord'
$ eval $(echo $STR | sed 's:^:V1=":; /###/ s::";V2=": ;s:$:":')
$ echo $V1
firstWord
$ echo $V2
secondWord

This is how I would do it with zsh: 这就是我用zsh做的方法:

myVAR="firstWord###secondWord"
<<<$myvar sed 's/###/ /' | read myFIRST mySECOND

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

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