gpt4 book ai didi

linux - 读取 'for' 循环中的完整行,带空格,带多个输入文件的制表符

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:11:52 25 4
gpt4 key购买 nike

看过'for'循环的文章。它根据空格、制表符或换行符等空格的出现进行拆分。为了解决这个问题,我有以下额外的命令:

IFS=$'\n'

但是当我尝试根据以下细节解决上述情况时(我有两个文件:'input1.txt''input.txt' txt' 在我的当前目录中):

BASH 命令:

bash script.sh 'input*'

下面是 script.sh 中的'for'循环 block

for line in $(cat $1)
...
...
done;

执行时出现以下错误:

cat: input1.txt input.txt*: No such file or directory

注意:我想cat这两个文件input1.txtinput .txt

最佳答案

通过重置 $IFS,您可以禁用分词,这会导致 $1 中的模式扩展被视为单独的文件名。这是以正确的方式执行此操作的另一个原因。但首先,假设您真的想将模式传递给脚本,而不是仅仅使用 bash script.sh input* 让 shell 将模式扩展为脚本的文件列表。那么你的循环应该是这样的

cat $1 | while IFS= read -r line; do
...
done

但是,如果任何匹配文件本身的名称中有空格,这将不起作用;使用 input a.txtinput b.txt$1 将扩展为 4 个单词 inputa.txtinputb.txt。相反,您应该真正让 shell 进行扩展并将每个匹配文件作为单独的参数传递:

bash script.sh input*

在你的脚本中:

for f in "$@"; do
while IFS= read -r line; do
...
done < "$f"
done

关于linux - 读取 'for' 循环中的完整行,带空格,带多个输入文件的制表符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35774850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com