-3

I am a beginner and I am wondering if I can get help with this, please. The code should read one line from a file, display it, meet a condition, and then move on to the next line and repeat for as many lines as are in the file. I have been able to come up with a way to do this but this would be better if it was a loop instead. This is what I have so far

output=$(cat urls.txt | sed -n '1p')
read -p  "Store $output y or n ?" deci 
if [ $deci == "y" ];
then  
sed -n '1p' urls.txt >> saved_domains.txt
fi 
output=$(cat urls.txt | sed -n '2p')
read -p  "Store $output y or n ?" deci
if [ $deci == "y" ];
then  
sed -n '2p' urls.txt >> saved_domains.txt
fi

And this goes on, line by line

phlow
  • 1
  • 2
  • 1
    Does this answer your question? [Read a file line by line assigning the value to a variable](https://stackoverflow.com/questions/10929453/read-a-file-line-by-line-assigning-the-value-to-a-variable) – rkta Nov 06 '20 at 12:16
  • 1
    Looping over the line numbers is a massive antipattern. Just accept the duplicate; ask a new question with your best effort based on the code in the duplicate if you still need help. – tripleee Nov 06 '20 at 12:20
  • Ack! This is a terrible approach. But, to fix one tiny little detail and still have a terrible approach (I suppose this one detail strikes me as too egregious to let slide), you should wrap your logic in a function and do something like: `foo() { output=$( sed -n "${1}p" urls.txt) ...; }` and then invoke the function in a loop. But....ick. Don't do this. – William Pursell Nov 06 '20 at 13:47
  • Yeah, still a serious newbie at this. It's already wrapped in a function but did not include that on here. Appreciate the input William – phlow Nov 06 '20 at 14:54

1 Answers1

0
#!/bin/bash
while read output
do
    read -p "Store $output y or n ?" deci < /dev/tty
    if [[ "$deci" == "y" ]]
    then
            echo "$output" >> saved_domains.txt
    fi
done < url.txt

You can read the url.txt file into an "output" variable through a while loop and use this to read the output from the user and append to the saved_domains.txt file accordingly.

One thing to note is the use of the < /dev/tty at the end of the read command for user input. This is not usually needed but as we are already reading from standard input through reading from the file, we need to specifically specify that we are reading from the terminal (/dev/tty)

Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18