0
ckim@ckim-ubuntu:~/test$ cat tt
#define a b
#define c d
ckim@ckim-ubuntu:~/test$ for i in `cat tt`; do echo $i; done
#define
a
b
#define
c
d

The $i variable is taking every single word seperated by space or enter. How can I make $i represent each line from the cat command? Either using for or while is ok for me and this is bash. Thank you!

ADD : I can iterate through the line by while read line; do echo $line; done < tt but I want to do something for each line, and if I pass this output to a for loop, it's all separated to each word.

Chan Kim
  • 397

2 Answers2

1

From comment from @glennjackman, I leared how to do it. This is what I originally wanted to do (grep a file and extract the file path in front of :).

ckim@ckim-ubuntu:~/U-BOOT/u-boot$ cat tt
dir0/Kconfig:config SUPPORT_SPL
dir1/Kconfig:select SUPPORT_SPL
dir2/Kconfig:select SUPPROT SPL
ckim@ckim-ubuntu:~/U-BOOT/u-boot$ while IFS= read -r i; do echo "${i%:*}"; done < tt
dir0/Kconfig
dir1/Kconfig
dir2/Kconfig
Chan Kim
  • 397
  • 1
    sed 's/:.*//' tt or cut -d: -f1 tt. Also, see https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice – Kusalananda Nov 17 '21 at 07:34
0

Your addition seems to work the way you want:

#!/bin/sh
while read line; do
    echo "$line"
done < tt

Output:

#define a b
#define c d
  • yes right. with this read comand, the whole line is substituted in the loop and I could do anything.(as I showed in my answer). I wasn't clear about it when i added the ADD:. – Chan Kim Nov 17 '21 at 06:05