I have a file in the following format and it is tab separated

a   k   testis  adult   male    8 week  rRNA
b   k   testis  adult   male    8 week  rRNA
c   k   testis  adult   male    8 week  rRNA

I want to do some operation on each line so I am using a while loop.I want to split each line on tab and then store let's say 6th column which is 8 week in a variable. I am using this code but I am not able to get what I want

while read -r line; do tmp=(${line///}); col6=${tmp[5]}; echo "$col6"; done < file.txt

This gives me 8 and not 8 week. 8 week has a space in between 8 and week and hence I want to split the line on tab.

up vote 7 down vote accepted

The array assignment tmp=(${line///}) splits the value on whatever characters IFS contains, which by default includes tabs, and spaces and newlines. (I don't see what the empty substitution does.) To split only on tabs, set IFS to this:

foo=$'a\tk\testis\tadult\tmale\t8 week\tRNA'
IFS=$'\t'
tmp=($foo)
echo "${tmp[5]}"

Though that still leaves globbing as an issue, and since you are already using while read, you could use read -a tmp (at least in Bash), it splits the input line based on IFS, and separates the fields to elements of the named array:

$ while IFS=$'\t' read -r -a tmp ; do
    echo "${tmp[5]}"
done <<< $'a\tk\testis\tadult\tmale\t8 week\tRNA'

That prints 8 week. The other upside with this is that the change in IFS is only in effect for the duration of the read, not for the rest of the script.

Of course, if we know the number/meaning of the fields, we could just have read split them to separate named variables:

... IFS=$'\t' read -r col1 col2 col3 ...

Or, if you only want to print that one column, use cut:

cut -d$'\t' -f 6  < file.txt
  • can you tell what -a tmp is doing?? – user3138373 Dec 13 '17 at 18:20
  • 2
    @user3138373 the -a flag tells read to store what it reads as an array. – terdon Dec 13 '17 at 18:23

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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