Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am trying the contents of an array into a file with each element of the array in a new line in the file.

IFS=$'\n'   
echo "${mtches[@]}" > sample1.txt 


The content of mtches is "qwe" and " asd". But the sample1.txt file contains qwe asd in a single line. Why is it not taking IFS value into the picture?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

You should use printf instead:

printf "%s\n" "${mtches[@]}"

Note

In bash, you should use "$@" instead of "$*", except you have a special reason. This reason is also applied to array. From man bash, section Arrays:

   Any  element  of  an  array may be referenced using ${name[subscript]}.
   The braces are required to avoid conflicts with pathname expansion.  If
   subscript  is  @  or *, the word expands to all members of name.  These
   subscripts differ only when the word appears within double quotes.   If
   the word is double-quoted, ${name[*]} expands to a single word with the
   value of each array member separated by the first character of the  IFS
   special variable, and ${name[@]} expands each element of name to a sep‐
   arate word.  When there are no array  members,  ${name[@]}  expands  to
   nothing.   If  the  double-quoted  expansion  occurs within a word, the
   expansion of the first parameter is joined with the beginning  part  of
   the  original  word,  and the expansion of the last parameter is joined
   with the last part of the original word.   This  is  analogous  to  the
   expansion  of  the  special  parameters * and @ (see Special Parameters
   above).

Only use ${array[*]} when you want join all array elements to a string.

share|improve this answer
    
How does that make a diference? –  Ashwin Apr 20 at 8:54
    

You want to use ${mtches[*]} instead.

When you use "${mtches[@]}", it doesn't matter what the value of $IFS is, bash will split the array into multiple arguments. What you want is a single argument with each array element joined by \n. ${mtches[*]} accomplishes this.

Also as a temporary way of setting $IFS, you can do:

( IFS=$'\n'; echo "${mtches[*]}" > sample1.txt )

Then you don't have to bother with setting it back.

share|improve this answer
    
pubs.opengroup.org/onlinepubs/9699919799/utilities/… <- POSIX reference (this does not apply only to bash). –  Mat Apr 20 at 8:52
    
Or use printf... –  jasonwryan Apr 20 at 8:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.