Dimitris Delis Dimitris Delis - 1 month ago 9
Bash Question

echo specific words from a variable containing text

I'm trying to use the echo command to print some specific words from a variable( that has a text in it ) as following :

for i in $variable
do
IFS="|" # the text is in format : word1|word2|word3
first=( "$i" )
echo ${first[1]}
IFS=$OlIFS # I have a OlIFS variable which I set in the beginning of the code as following : OlIFS=$IFS
done


The result is a ton of empty lines. I guess the problem is in the echo command but I'm not too sure
The $variable contains a text in the format of :

word1line1|word2line1|word3line1
word1line2|word2line2|word3line2


Expected Output is :

word1line1
word1line2
.
.
etc


If I use ${first[2]}, I want to have word2 as result instead of word1

Answer

Your problem is that you're quoting the variable in the array assignment. In this case, you do want to leave it unquoted to get the word splitting effect.

Quoted:

$ variable="word1line1|word2line1|word3line1
word1line2|word2line2|word3line2"

$ for word in $variable; do ( IFS='|'; words=("$word"); echo "${words[0]}" ); done
# ............................................^.....^
word1line1|word2line1|word3line1
word1line2|word2line2|word3line2

Unquoted:

$ for word in $variable; do ( IFS='|'; words=($word); echo "${words[0]}" ); done
# ............................................^....^
word1line1
word1line2

I'm using a subshell to localize the IFS assignment