Home > Net >  How to get variables from text in Shell Scripting?
How to get variables from text in Shell Scripting?

Time:08-06

I want to get variables from text, for example our text is: "Barren Gates - Devil", we want get two variables from this text. First variable should be everything before - mark, (not including last space, it shouldn't finish with space.) second variable should be everything after - mark. For example:

artist=Barren Gates
songname=Devil

How can I do it?

CodePudding user response:

You could use sed:

text="Barren Gates - Devil"
artist=`echo "$text" | sed 's/ - .*//'`
songname=`echo "$text" | sed 's/.*- //'`

If you are using bash then you can use its built-in suffix and prefix removal:

artist=${text% - *}
songname=${text#* - }
  • Related