Home > Blockchain >  How to strip and split a string which contains an escape sequence in bash?
How to strip and split a string which contains an escape sequence in bash?

Time:09-21

I have a string. For example

STR="          Hello, World    I'm\ new\ here  "

and what I want to receive is an array like this

"Hello,"
"World"
"I'm new here"

or at least something iterable so I can iterate over these "words" and do manipulations with them. Thanks!

CodePudding user response:

When you don't mind a solution using more steps, you can use

echo "          Hello, World    I'm\ new\ here  " |
  sed 's/\\ /\r/g' | grep -Eo "[^ ]*" | sed 's/\r/ /g'

One pipe less makes the regex more complicated:

echo "          Hello, World    I'm\ new\ here  " | 
  grep -Eo "([^ ]*([\] )*) [^ ]*" | sed 's/\\ / /g'

With GNU sed you can have a different approach:

echo "          Hello, World    I'm\ new\ here  " |
  sed -z 's/ /\n/g; s/\\\n/ /g' | grep .

CodePudding user response:

You can simply use read.

$ STR="          Hello, World    I'm\ new\ here  "
$ read -a x <<< "$STR"
$ declare -p x
declare -a x=([0]="Hello," [1]="World" [2]="I'm new here")

read performs word-splitting on its input as usual; the -a option causes each word to be stored as a separate element of the array, rather than storing words in individual variables. read's default behavior is to replace escape sequences with the character they represent: in this case, '\ ' represents ' '.

  • Related