1

I have this sample text file text.txt that is in the form

fruits    vegetables
apples    cucumbers
oranges    squash

and it is tab delimited.

I would like to loop through the file line by line, and extract each column value.

Below is the code the code I have tried.

while read p
do
  echo "Line"
  fruit="$(cut -f 1 $p)"

  echo "${fruit}"
done <test.txt

My expected output should be something like:

Line
fruits
Line
apples
Line
oranges

Instead I get this output:

Line
cut: fruits: No such file or directory
cut: vegetables: No such file or directory

Line
cut: apples: No such file or directory
cut: cucumbers: No such file or directory

Line
cut: oranges: No such file or directory
cut: squash: No such file or directory
9
  • while IFS=$'\t' read -r col1 rest; do echo "$col1"; done. There's no reason to use cut or anything like it. Commented Jul 19, 2019 at 16:38
  • 2
    ...that said, in general, you should show your actual output, not just expected output. Commented Jul 19, 2019 at 16:39
  • ...to explain your immediate bug: cut -f 1 $p expects $p to expand to a filename, which is what cut then tries to read from. Commented Jul 19, 2019 at 16:40
  • See above running successfully @ ideone.com/XMEpTP; I'm going to be closing this question with a duplicate momentarily. Commented Jul 19, 2019 at 16:41
  • I just added also the actual output. How would I modify your script to print the second filed as well? Commented Jul 19, 2019 at 16:44

1 Answer 1

0

I would like to loop through the file line by line, and extract each column value

Is awk not suitable ?

awk '{ print "Line"; print $1 }' < test.txt
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.