0

I have a test file like below. (but the actual file has 1000+ lines and many columns)

apple,2
mango,5
coconut,10

I want to print this file as below.

I have apple and the count is 2
I have mango and the count is 5
I have coconut and the count is 10

I tried while read line with awk -F ',' '{print $1}', but im not getting the actual output. Can someone help me on this?

TheDataGuy
  • 2,712
  • 6
  • 37
  • 89

3 Answers3

6

You can use awk like this:

awk -F, '{print "I have", $1, "and the count is", $2}' file

I have apple and the count is 2
I have mango and the count is 5
I have coconut and the count is 10

Though awk is recommended but if you are looking for a bash loop then use:

while IFS=, read -r f c; do
    echo "I have $f and the count is $c"
done < file
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • If I want to add single quote `'` like `'apple' ` how can I edit this? – TheDataGuy Aug 08 '18 at 08:13
  • 1
    Using `awk` you can do: `awk -F, '{print "I have \047" $1 "\047 and the count is", $2}' file` OR using `bash` use: `while IFS=, read -r f c; do echo "I have '$f' and the count is $c"; done < file` – anubhava Aug 08 '18 at 08:15
1

Here is one in sed. Replace the beginning of each line and the comma with related strings:

$ sed 's/^/I have /;s/,/ and the count is /' file
I have apple and the count is 2
I have mango and the count is 5
I have coconut and the count is 10
James Brown
  • 36,089
  • 7
  • 43
  • 59
1

If it's a small file, you can use read to split the line.

while IFS=, read fruit count; do
  echo "I have $fruit and the count is $count"
done < file.txt

For larger files, it is inefficient to iterate using bash, and something like awk to read the entire file would be more appropriate.

chepner
  • 497,756
  • 71
  • 530
  • 681