迭代文件并将行作为位置参数发送到另一个文件

迭代文件并将行作为位置参数发送到另一个文件

我想迭代包含以下格式的日期(名为dates.txt)的文件:

2009 08 03 08 09
2009 08 03 09 10
2009 08 03 10 11
2009 08 03 11 12
2009 08 03 12 13
2009 08 03 13 14

并将每行的每个字段作为位置参数传递给另一个脚本。

即:另一个脚本是通过在命令行中输入以下内容来执行的:

$ . the_script 2009 08 03 08 09

我努力了for i in $(./dates.txt);do echo ${i};done

但得到:

./dates: line 1: 2009: command not found
./dates: line 2: 2009: command not found
./dates: line 3: 2009: command not found
./dates: line 4: 2009: command not found
./dates: line 5: 2009: command not found
./dates: line 6: 2009: command not found

从这里我可以看出它正在通过每条线工作,但也许在每个领域都挂断了?

由于上述原因,我还无法弄清楚如何将读取行作为位置参数传递给其他脚本。也不知道在哪里工作?请帮助!

答案1

也许你的意思是这样的?

while read -d $'\n' i; do echo $i;done <./dates

while read -d $'\n' i; do . the_script $i;done <./dates

答案2

.如果不需要采购( ),这听起来像是一份工作xargs:

xargs -a dates.txt -rL1 the_script
  • xargs读取一行输入,然后将其用作指定命令的参数。默认行分隔符是换行符。
  • 我们可以从其他命令将数据传输到它,或者使用-a.
  • 由于每次调用脚本只使用一行,因此我们指定-r(如果行为空则不运行)和-L(每次调用最多使用 N 行)选项。

答案3

如果脚本不在同一目录中,请在命令中使用cat并确保使用正确的文件名路径。如果列表是,dates.txt则使用$(cat ./dates.txt).此处编辑错字。包含 .txt

这是一个例子:

名为 的日期列表dates.txt

2009 08 03 08 09
2009 08 03 09 10
2009 08 03 10 11
2009 08 03 11 12
2009 08 03 12 13
2009 08 03 13 14

一个脚本的命名是lstdates.sh为了呼应该列表中的行星。已编辑 它在内部字段分隔符 (IFS) 的子 shell 中运行1在子 shell 之外不会更改2

#!/bin/bash
# Listing each date as an argument for `the_script`.

# Parenthesis runs in a subshell    
( 
  # IFS line break
  IFS=$'\012'
  for dates in $(cat ./dates.txt)
  do
    echo $(./the_script $dates)
  done
)

默认情况下,IFS 将每个空格识别为字段的结尾。IFS=$'\012'将每个新行识别为字段的结尾。如果每行都用双引号引起来,例如"2009 08 03 08 09",则默认的 IFS 将起作用。

the_script仅包含以下内容。

#!/bin/bash
echo $1

参考:高级 Bash 脚本指南第 11 章循环和分支

相关内容