Reputation: 459
I'm trying to copy over only specific words from 1 text file to another.
this is what is inside my username2.txt:
jason,visitor
mark,staff
orlando,visitor
I'm trying to copy over only jason and orlando to another txt file so it'll just be like:
jason
orlando
this is currently my bash script (as of right now, it only creates a blank txt file):
#!/bin/bash
username="username2.txt"
while IFS=, read username1 group1; do
if [ $group1 = "visitor" ]; then
awk $username1 $username > reportvisitors.txt
fi
done < $username
Upvotes: 3
Views: 427
Reputation: 336
You have to edit the line 7 to
echo $username1 >> reportvisitors.txt
The Code should look like
#!/bin/bash
This part makes sure that an already existing file with the name is deleted
FILE=reportvisitors.txt
if test -f "$FILE"; then
rm $FILE
fi
from here on I have only edited line 5
username="username2.txt"
while IFS=, read username1 group1; do
if [ $group1 = "visitor" ]; then
echo $username1 >> reportvisitors.txt
fi
done < $username
Upvotes: 0
Reputation: 88731
Replace
awk $username1 $username > reportvisitors.txt
with
echo "$username1" >> reportvisitors.txt
Update
#!/bin/bash
username="username2.txt"
while IFS=, read username1 group1; do
if [ "$group1" = "visitor" ]; then
echo "$username1"
fi
done < $username > reportvisitors.txt
Upvotes: 1
Reputation: 133600
This could be easily done with awk
and we do not need to use a while loop for this since awk
itself could read Input_file itself.
username="username2.txt"
awk -F, '$2=="visitor"{print $1}' "$username" > "reportvisitors.txt"
Explanation: Simple explanation is, making field separator as ,
for all lines of Input_file(which is a shell variable named username
). Then inside main program checking condition $2=="visitor"
to check if 2nd field is visitor then printing 1st column. At last of this awk
program sending output to reportvisitors.txt
.
Upvotes: 4