Shell 脚本,用于在具有 space 分隔字段的文件的每一行上执行命令
Shell script to execute command on each line of a file with space-delimited fields
我正在尝试编写一个 shell 脚本,该脚本逐行读取文件并执行命令,其参数取自每行的 space 分隔字段。
更准确地说,我需要使用 wget 从第二列中给出的 URL 下载文件到第一列中给出的路径。但我不知道如何加载此文件并获取脚本中的值。
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
期望的输出是
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
在 bash 中使用 read 和 while 循环逐行遍历文件并在每次迭代时调用 wget:
while read -r NAME URL; do wget "$URL" -o "$NAME"; done < File.txt
您可以使用 for
循环和 seq
的输出进行计数,如下所示:
在 bash 中,您可以使用 $((C+3))
添加数字。
这会让你:
COUNT=6
OFFSET=18
for C in `seq "$((COUNT-1))"`; do
wget https://example.com/temp/file-${C}.log -o file-$((C+OFFSET-1)).log
done
wget https://example.com/temp/file-${COUNT}.pdf -o file-$((COUNT+OFFSET-1)).pdf
编辑: 抱歉,我看错了你的问题。因此,如果您有一个包含文件映射的文件,您可以使用 awk 获取 URL 和 FILE,然后进行下载:
cat File.txt | while read L; do
URL="$(echo "${L}" | awk '{print }'"
FILE="$(echo "${L}" | awk '{print }'"
wget "${URL}" -o "${FILE}"
done
将文件转换为命令的参数是 xargs
的工作:
xargs -a File.txt -L1 wget -o
xargs -a File.txt
: 从 File.txt
文件中提取参数。
-L1
: 将 1 行的所有参数传递给命令。
wget -o
将参数传递给 wget
命令。
我正在尝试编写一个 shell 脚本,该脚本逐行读取文件并执行命令,其参数取自每行的 space 分隔字段。
更准确地说,我需要使用 wget 从第二列中给出的 URL 下载文件到第一列中给出的路径。但我不知道如何加载此文件并获取脚本中的值。
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
期望的输出是
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
在 bash 中使用 read 和 while 循环逐行遍历文件并在每次迭代时调用 wget:
while read -r NAME URL; do wget "$URL" -o "$NAME"; done < File.txt
您可以使用 for
循环和 seq
的输出进行计数,如下所示:
在 bash 中,您可以使用 $((C+3))
添加数字。
这会让你:
COUNT=6
OFFSET=18
for C in `seq "$((COUNT-1))"`; do
wget https://example.com/temp/file-${C}.log -o file-$((C+OFFSET-1)).log
done
wget https://example.com/temp/file-${COUNT}.pdf -o file-$((COUNT+OFFSET-1)).pdf
编辑: 抱歉,我看错了你的问题。因此,如果您有一个包含文件映射的文件,您可以使用 awk 获取 URL 和 FILE,然后进行下载:
cat File.txt | while read L; do
URL="$(echo "${L}" | awk '{print }'"
FILE="$(echo "${L}" | awk '{print }'"
wget "${URL}" -o "${FILE}"
done
将文件转换为命令的参数是 xargs
的工作:
xargs -a File.txt -L1 wget -o
xargs -a File.txt
: 从File.txt
文件中提取参数。-L1
: 将 1 行的所有参数传递给命令。wget -o
将参数传递给wget
命令。