0
9848012341 100 10
9848012342 126 200
9848012343 5 3
9848012344 23 0
9848012345 69 2
9848012346 0 1
9848112341 80 4
9848112342 555 300
9848112343 700 1000
9848112344 350 679
9848112345 270 86
9848112346 9 0
9848112347 1 3

This is the data in text file named as file.txt. Now I want shell script using while loop to get output of only first column...

#!/bin/bash
while 
read column
do 
echo "$column"
done< file.txt

so using this I'm getting my total text file output. But I want to display only the first column of the text file and I'm not getting it. Could you please help me!!

Dominique
  • 16,450
  • 15
  • 56
  • 112

1 Answers1

1

A much better solution is to use cut or Awk.

If your file is space-delimited,

cut -d ' ' -f1 file

or

awk '{print $1}' file

The problem with your approach is that you read all the columns into one variable. The shell will split into multiple variables if you ask it to. (Probably also remember -r.)

while read -r first others; do
    echo "$first"
done <file

But the shell is hopelessly slow compared to a dedicated tool; you basically want to avoid while read if at all possible. See also while read loop extremely slow compared to cat, why?

If you need more columns, specify more variables. Again, the shell splits on whitespace (or more generally on the value of IFS) into as many variables as you specify, with the remining columns in the last variable if you specify fewer variables than columns.

The -r option to read disables some pesky behavior around backslashes which basically nobody likes or wants but which was the default behavior in the original Bourne shell, and thus retained for backwards compatibility.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Using cut and awk i got the result. But i want to find out using while loop and i got the result from the information you shared. Now in the same way how to get the output of only second column as well as third column using the while loop? – sureshvarma_pithani Jan 17 '22 at 10:28
  • The shell splits into as many variables as you specify; try `while read -r first second third rest`; but generally, please avoid piling on new requirements. If you are completely new to the shell, perhaps read an introduction before you start to ask questions. – tripleee Jan 17 '22 at 10:29
  • Where i can get the introduction to these..? can you suggest me a good website for learning online?! – sureshvarma_pithani Jan 17 '22 at 10:33
  • The [Stack Overflow `bash` tag info page](/tags/bash/info) has links to online resources near the bottom of the page. – tripleee Jan 17 '22 at 10:35