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.

3

2 Answers 2

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
1
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
1
  • 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, 2021 at 6:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.