JohnTheWizard
JohnTheWizard

Reputation: 95

How to split words in bash

Good evening, People

Currently I have an Array called inputArray which stores an input file 7 lines line by line. I have a word which is 70000($s0), how do I split the word so it is 70000 & ($s0) separate?

I looked at an answer which is on this website already but I couldn't understand it the answer I looked at was:

s='1000($s3)'
IFS='()' read a b <<< "$s"
echo -e "a=<$a>\nb=<$b>"

giving the output a=<1000> b=<$s3>

Upvotes: 0

Views: 1851

Answers (1)

glenn jackman
glenn jackman

Reputation: 247240

Let me give this a shot.

In certain circumstances, the shell will perform "word splitting", where a string of text is broken up into words. The word boundaries are defined by the IFS variable. The default value of IFS is: space, tab, newline. When a string is to be split into words, any sequence of this set of characters is removes to extract the words.

In your example, the set of characters that delimit words are ( and ). So the words in that string that are bounded by the IFS set of characters are 1000 and $s3

What is <<< "$s"? This is a here-string. It's used to send a string to some command's standard input. It's like doing

echo "$s" | read a b

except that form doesn't work as expected in bash. read a b <<< "$s" works well.

Now, what are the circumstances where word splitting occurs? One is when a variable is unquoted. A demo:

IFS='()'
echo "$s" | wc    # 1 line, 1 word and 10 characters
echo $s | wc      # 1 line, 2 words and 9 characters

The read command also splits a string into words, in order to assign words to the named variables. The variable a gets the first word, and b gets all the rest.

The command, broken down is:

  IFS='()' read a b <<< "$s"
# ^^^^^^^                      1
#                   ^^^^^^^^   2
#          ^^^^^^^^            3
  1. only for the duration of the read command, assign the variable IFS the value ()
  2. send the string "$s" to read's stdin
  3. from stdin, use $IFS to split the input into words: assign the first word to variable a and the rest of the string to variable b. Trailing characters from $IFS at the end of the string are discarded.

Documentation:

Hope that helps.

Upvotes: 1

Related Questions