Bad_Dream wrote:im trying to figure out how to edit trivia questions to change them from one format to another
the questions are in this format :
spring:What season is the setting for Shakespeare's A Midsummer Nights Dream ?
and i need them in this format:
What season is the setting for Shakespeare's A Midsummer Nights Dream ?*spring
i have no idea where to start to write a script to do this and was hoping someone could point me in the right direction! thanks

Since Bad_Dream is a newbie, I've decided not to use regular expressions, but a while loop.
Pros of while loop
- Writes to the same file - can be executed many times for a group of trivia files
- Simple to write
Cons of for loop
- Slower than regular expressions
Pros of regular expressions
- Edits the file directly, does not generate a new one
- Faster than for loop
Cons of regular expressions
- Not as easy to write.
I'll start off with an explanation and a commented script.
First, we run a big while loop. In this while loop, we assign variable 'string' to the current line of the file. Then, the position of substring ":" is found. The substrings are then extracted. With this each line can be rearranged to obtain the result.
Code:
- Code: Select all
#!/bin/bash
FILENAME="trivia1.txt"
while read string
do
# Start of line parsing.
echo $string # Prints out the string.
i=`expr index "$string" :` # Obtain index of :
# Extracts a substring of position x and position x + 1, or the letter at position x
# Checks if equal to a colon.
answer=${string:0:$((i-1))} # Obtains everything before the colon
question=${string:$i} # Obtains everything after the colon
echo "$answer"
echo "$question"
result=`echo $question*$answer`
echo $result
echo $result >> ./result.txt
done < $FILENAME # Reads the file.
echo ""
echo "File conversion has finished. Check result.txt in this directory."
echo "Press enter to exit"
read enter # Just a goodie, no need to remember this
Now, in the terminal, run (make sure you are in the correct directory):
- Code: Select all
wei2912@ubuntu-desktop ~ $ chmod +x ./bash.sh
wei2912@ubuntu-desktop ~ $ ./bash.sh
testing:Testing question
testing
Testing question
Testing question*testing
File conversion has finished. Check result.txt in this directory.
Press enter to exit
wei2912@ubuntu-desktop ~ $
Try running this script with a file trivia1.txt containing answers and questions. Make sure there is an endline after the last setence for this script to work properly.
If you're interested in editing this script, contact me, else simply change the variable FILENAME to what the name of your file is.
This script is extremely efficient, it can convert 4500 lines in 8 seconds.