在“for"循环中读取带有空格的完整行,带有多个输入文件的选项卡 [英] Reading complete line in 'for' loop with spaces, tabs with multiple input files

查看:33
本文介绍了在“for"循环中读取带有空格的完整行,带有多个输入文件的选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have seen articles of 'for' loop. It splits on the occurance of whitespace like space, tab, or newline. To get ride of that issue i have following extra line of command:

IFS=$'
'

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

But when i try to solve the above scenario on following details (i have two files: 'input1.txt' and 'input.txt' on my current directory):

BASH 命令:

bash script.sh 'input*'

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

Below is 'for' loop block in script.sh

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

执行时出现以下错误:

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

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

Note: I want to cat both files input1.txt and input.txt

推荐答案

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

By resetting $IFS, you disable the word-splitting that would cause the expansion of the pattern in $1 to be treated as separate file names. This is another reason to do this the right way. But first, let's say you really want to pass a pattern to your script, rather than just use bash script.sh input* to have the shell expand the pattern to list of files for your script. Then your loop should be something like

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

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

However, this won't work if any of the matching files themselves have whitespace in their names; with input a.txt and input b.txt, $1 will expand to 4 words input, a.txt, input, and b.txt. Instead, you should really let the shell do the expansion and pass each matching file as a separate argument:

bash script.sh input*

在你的脚本中:

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

这篇关于在“for"循环中读取带有空格的完整行,带有多个输入文件的选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆