如何在 bash 中一次一行地将变量传递给脚本?
How can I pass variables to a script one line at a time in bash?
我有一份文件和标题列表如下:
Title file1.txt
Title2 file2.txt
Title3 file3.txt
如何将它逐行传递给脚本,将第 1 列和第 2 列设置为单独的变量。例如
将标题作为 $1 和 file1.txt 作为 $2 发送到我的脚本。
然后将 Title2 作为 $1 和 file2.txt 作为 $2 发送到同一个脚本。
我不知道是否有更简单的方法来做到这一点,但如果您能提供帮助,我们将不胜感激。
尝试:
for i in "Title file1.txt" "Title2 file2.txt" "Title3 file3.txt"; do Title $i; done
这实际上类似于:
$ for i in "a b" "c d" "e f"; do echo $i; done
a b
c d
e f
您可以尝试制作其他 运行 您的目标脚本:
#! /bin/bash
ls /path/where/files/stay >> try.txt
a=1
while [ $a -lt 7 ]
do
./script $(sed "$a"'q;d' try.txt) $(sed "$(($a+1))q;d" try.txt)
a=$(($a+2))
done
此脚本将 运行 您的脚本从文件中获取您喜欢的变量。
逐行读取文件,使用参数扩展提取标题和文件名。
while read -r title file ; do
echo Title is "$title", file is "$file".
done < input.lst
如果标题可以包含空格,那就有点复杂了:
while read -r line ; do
title=${line% *} # Remove everything from the first space.
title=${title%%+( )} # Remove trailing spaces.
file=${line##* } # Remove everything up to the last space.
echo Title is "$title", file is "$file".
done < input.lst
我有一份文件和标题列表如下:
Title file1.txt
Title2 file2.txt
Title3 file3.txt
如何将它逐行传递给脚本,将第 1 列和第 2 列设置为单独的变量。例如
将标题作为 $1 和 file1.txt 作为 $2 发送到我的脚本。 然后将 Title2 作为 $1 和 file2.txt 作为 $2 发送到同一个脚本。
我不知道是否有更简单的方法来做到这一点,但如果您能提供帮助,我们将不胜感激。
尝试:
for i in "Title file1.txt" "Title2 file2.txt" "Title3 file3.txt"; do Title $i; done
这实际上类似于:
$ for i in "a b" "c d" "e f"; do echo $i; done
a b
c d
e f
您可以尝试制作其他 运行 您的目标脚本:
#! /bin/bash
ls /path/where/files/stay >> try.txt
a=1
while [ $a -lt 7 ]
do
./script $(sed "$a"'q;d' try.txt) $(sed "$(($a+1))q;d" try.txt)
a=$(($a+2))
done
此脚本将 运行 您的脚本从文件中获取您喜欢的变量。
逐行读取文件,使用参数扩展提取标题和文件名。
while read -r title file ; do
echo Title is "$title", file is "$file".
done < input.lst
如果标题可以包含空格,那就有点复杂了:
while read -r line ; do
title=${line% *} # Remove everything from the first space.
title=${title%%+( )} # Remove trailing spaces.
file=${line##* } # Remove everything up to the last space.
echo Title is "$title", file is "$file".
done < input.lst