Reputation: 67
I would like to ask one qustion: I have something like this. WEDI_RC is a txt file and I want read it line by line, take first column and store it to variable "name". When I echo 4th line it successfully write first column ($1). Then I want to compare it with $list, if it matched then add it to $list and write. It should write just one time every name. See example below:
Input:
file1 1234 5667
file1 1234 4566
file1 1234 23456
file1 1234 23467
file2 1234 23456
file3 1234 12345
Output:
file1
file2
file3
My code:
list=""
while read -r line
do
name=$(echo $line | awk -F'[ ]' '{print $1}')
echo $name
if [ "$name" = "$list" ]; then
echo $name
list=$'$list\n$name'
echo "$list"
fi
done < $WEDI_RC
Upvotes: 1
Views: 96
Reputation: 18855
Back to the basics you should use cut -f1 -d" "
to get the first column delimited by a space character, sort
to sort the result and uniq
to display uniq results
cut -f1 -d" " WEDI_RC | sort | uniq
Or as suggested in other answer sort -u
is similar to sort | uniq
cut -f1 -d" " WEDI_RC | sort -u
Upvotes: 0
Reputation: 16059
If I understood your requirement, you want to show different names that appear along the first column, you can do it with something like this:
previousColumn=""
while read -r column1 column2 column3; do
if [ "$previousColumn" != "$column1" ]; then
echo "$column1"
previousColumn=$column1
fi
done < $WEDI_RC
Upvotes: 1
Reputation: 113964
If I understand correctly, you want to obtain a list of unique names from the first column of the file WEDI_RC
. If that is the case:
$ awk '{print $1}' WEDI_RC | sort -u
file1
file2
file3
This can also be done without use of sort
, although the order in which the names are printed is not guaranteed:
$ awk '{a[$1]=1} END{for (name in a)print name}' WEDI_RC
file1
file2
file3
If it is known in advance that the names in the WEDI_RC file are sorted, then another approach is:
$ awk 'prior!=$1{print $1} {prior=$1}' WEDI_RC
file1
file2
file3
Upvotes: 1