简体   繁体   中英

store value of cat to a variable in unix

I need to assign two columns (column 2 and 6) in a text file to a variable as an array. so that i can call them back element by element. the code below puts the whole column as one string element in k and l. and the echo command will not return anything as everything is stored in the first element

k=`(cat mydata.txt | awk '{print $2}')`
l=`(cat mydata.txt | awk '{print $6}')`
echo ${k[2]}
echo ${l[2]}

below is an example of data set i used.

60594412 56137844 48552535 44214019 44121294 28652826 21975449 21718959 18208824 18004925 13299946 12969796 11990006 10435260 9992615 9975420 9223972 8918246 8730367 7723045 7316105 6772270 6301570 5662296 4653831 3769516 3343899 2639162 2393169 1992206 1838674 1681498 1563810 1389679 1267762 1253490 1205487 940968 718249 702722 655069 649121 619911 437735 284727 264334 252627 233213 185924 177421 160412 156581 143128 107247 87194 81369 74594 74185

Swap the order of the parentheses and backticks.

k=(`cat mydata.txt | awk '{print $2}'`)
l=(`cat mydata.txt | awk '{print $6}'`)

Stylewise, you could get rid of the useless use of cat and also change the backticks to $(...) , which is generally preferable.

k=( $(awk '{print $2}' mydata.txt) )
l=( $(awk '{print $6}' mydata.txt) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM