-1

Just need some help with a while read file from a specific column

I have a file with a few columns and I want to use while loop for a specific column
123 50012 1111
235 40023 2222
674 30021 3333

while read -a  line; do echo -e ${line[0]} > /dev/null;
echo "this is $line"
done < /location/file

it gives the correct info

this is 123
this is 235
this is 674

It works fine until I run the script, it stops at first line

this is 123

and stops.

If I place the column 0 into a separate file and run it with a script using a different way it works fine.

while IFS= read -r -u "$fd_num" line; do
script goes here...
done {fd_num}< /location/file

this works great, but I would like to keep everything in one file.

Any help would be appreciated

Max
  • 27
  • 8
  • 1
    Check for windows line endings aka carriage returns from the file in questions. Also put a shebang on your script and paste it at https://shellcheck.net – Jetchisel Jun 30 '21 at 00:02

2 Answers2

1

Given:

$ cat file
123 50012 1111
235 40023 2222 
674 30021 3333

You can do in Bash (works for tabs or spaces):

while read -r -a arr; 
    do printf "%s\n" "${arr[0]}"; # NOTE QUOTING!
done <file

If there is a possibility the last line is not properly terminated:

while IFS= read -r line || [[ -n $line ]]; do 
    arr=($line)         #purposefully does not have quoting
    printf "%s\n" "${arr[0]}"; 
done <file

Or use cut (assuming that is space, ' ', delimited:

cat file | cut -d ' ' -f 1    

Or awk (space or tabs):

awk '{print $1}` file

Any of those prints:

123
235
674

All three work with \r\n or \n on a unix machine (can't say for Windows...)

dawg
  • 98,345
  • 23
  • 131
  • 206
  • thank you for the response, it works just like mine, but when running script stops at first line. I have made it work fine when that column 0 in a separate file using `while IFS= read -r -u "$fd_num" line; do` `done {fd_num}< /location/file` but I would like to have everything in one file. – Max Jun 30 '21 at 00:12
1

The read command already splits the line based on the separators of $IFS (and with the default IFS, splits on sequences of space/tab).

You can do

while read -r col1 restOfList; do
    echo "this is $col1"
done < filename
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • your approach is fine as well, but it will stop at the first line when reading the file when running the script. – Max Jun 30 '21 at 01:18
  • 2
    Uh, no, it will not. Perhaps you have a more complex command inside the loop which eats standard input; then this is a duplicate of https://stackoverflow.com/questions/13800225/shell-script-while-read-line-loop-stops-after-the-first-line – tripleee Jun 30 '21 at 04:01
  • ok thank you, that would probably be the case – Max Jun 30 '21 at 07:07