Ask Your Question
3

How can shell script be utilized to change questions in a text file into JSON format?

asked 2021-05-22 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-06-30 15:00:00 +0000

plato gravatar image

One possible solution using a shell script is:

  1. Read the input text file line by line using a loop and store each line in a variable.
  2. Identify the lines containing the questions by checking if they end with a question mark "?".
  3. For each question line, extract the question text by removing the trailing question mark and any leading/trailing white spaces.
  4. Create a JSON object for each question with a "question" key and the extracted text as its value.
  5. Append each JSON object to a list of questions.
  6. Output the final list of questions in JSON format by enclosing the list in square brackets "[ ]" and separating each object with a comma ",".

Here's a sample shell script that implements this logic:

#!/bin/bash

# Input and output file paths
INPUT_FILE="questions.txt"
OUTPUT_FILE="questions.json"

# Start with an empty list of questions
questions=()

# Read the input file line by line using a while loop
while read line; do
  # Check if the line ends with a question mark
  if [[ "$line" == *'?' ]]; then
    # Extract the question text by removing the question mark and any white spaces
    question=$(echo "$line" | sed 's/\s*\?\s*$//')
    # Create a JSON object for the question
    question_json="{\"question\":\"$question\"}"
    # Append the question JSON to the list
    questions+=("$question_json")
  fi
done < "$INPUT_FILE"

# Output the list of questions in JSON format
echo "[" > "$OUTPUT_FILE"
echo "${questions[@]}" | tr ' ' '\n' >> "$OUTPUT_FILE"
echo "]" >> "$OUTPUT_FILE"

Note that this script assumes that the input text file contains one question per line and that the questions are independent of each other (i.e., they don't reference each other or depend on any context). If your use case is more complex, you may need to adjust the script accordingly.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-22 11:00:00 +0000

Seen: 10 times

Last updated: Jun 30 '21