Sunday, February 20, 2022

[SOLVED] Shell script to execute command on each line of a file with space-delimited fields

Issue

I am trying to write a shell script that reads a file line by line and executes a command with its arguments taken from the space-delimited fields of each line.

To be more precise, I need to download a file from an URL which is given in the second column to the path given in the first column using wget. But I don't know how to load this file and get the values in script.

File.txt

file-18.log https://example.com/temp/file-1.log
file-19.log https://example.com/temp/file-2.log
file-20.log https://example.com/temp/file-3.log
file-21.log https://example.com/temp/file-4.log
file-22.log https://example.com/temp/file-5.log
file-23.pdf https://example.com/temp/file-6.pdf

Desired output is

wget url[1] -o url[0]

wget https://example.com/temp/file-1.log -o file-18.log
wget https://example.com/temp/file-2.log -o file-19.log
...
...
wget https://example.com/temp/file-6.pdf -o file-23.pdf

Solution

Use read and a while loop in bash to iterate over the file line-by-line and call wget on each iteration:

while read -r NAME URL; do wget "$URL" -o "$NAME"; done < File.txt


Answered By - shilch
Answer Checked By - Mary Flores (WPSolving Volunteer)