LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   loop iterateration problem while reading .txt file (https://www.linuxquestions.org/questions/linux-newbie-8/loop-iterateration-problem-while-reading-txt-file-4175593000/)

pimpant 11-05-2016 10:57 PM

loop iterateration problem while reading .txt file
 
I got .txt file which its content is
-
5742060626,Ms.Pimpan Tantivaravong,Female
5742065826,Ms.Kaotip Tanti,Female
5742066666,Ms.Punbun Tan,Female
-
I create an interface script to add list in this file
First, I have to compare the input id with the exitsting id in a list.
I use cut command to read only 1st column of .txt file.
But,I got a problem when I am trying to compare it.

Here is my code.

-
!/bin/bash
#
datafile='student-2603385.txt'
while read p;
do

if [ "$id" == (echo $p | cut -d, -f1) ]
then
echo 'duplicate id'

fi
done <$datafile
-

could anyone suggest me, how should I do ?
Thank you

grail 11-06-2016 12:22 AM

Couple of things:

1. Please use [code][/code] tags around the code and data

2. Semi-colon after 'p' not required if 'do' is on next line

3. 'id' is never set

4. Prefer [[]] over [] see here for reasons

5. () places commands in a sub-shell, whereas, $() will return the value of the commands to the current shell

6. Get into the habit of quoting all variables until you know what you are doing and when it is desired to not have them quoted

7. Instead of cut you could also use parameter substitution

8. Another alternative would be to set IFS prior to 'read' so that the values are split for you

John VV 11-06-2016 01:54 PM

Quote:

8. Another alternative would be to set IFS prior to 'read' so that the values are split for you
ifs works great for CSV files
-- NOT the same as your issue but an example

recently i hacked this together
Code:

#!/bin/bash
INPUT=aa1.csv
OLDIFS=$IFS
IFS=,
[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }

while read name size lat long
 do

echo " Location "$name" "Sol/Ceres" "
echo  "  { "
echo  "    LongLat [ $long  $lat 0 ] "
echo  "  Size  $size  "
echo  "  Type  "AA" "
echo  "  } "

 done < $INPUT
 IFS=$OLDIFS

reads through the csv line and pasts parte into a new file

to extract a few sections in a csv line and formatting into what would look like a xml file

from this
Code:

"Abellio","Ceres",32,33.2,293.09,"Planetocentric  +East  0 - 360","Approved","Dec 4, 2015","Gaul god of the apple tree.",
"Achita","Ceres",40,25.82,65.96,"Planetocentric  +East  0 - 360","Approved","Sep 21, 2015","Nigerian god of agriculture.",

to this
Code:

Location "Abellio" "Sol/Ceres"
  {
    LongLat [ -293.09  33.2 0 ]
  Size  32 
  Type  "AA"
  }
 Location "Achita" "Sol/Ceres"
  {
    LongLat [ 65.96  25.82 0 ]
  Size  40 
  Type  "AA"
  }



All times are GMT -5. The time now is 11:18 PM.