在'for'循环中读取带有空格,带有多个输入文件的制表符的完整行 [英] Reading complete line in 'for' loop with spaces, tabs with multiple input files
问题描述
我看过 '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=$'\n'
但是当我尝试在以下详细信息上解决上述情况时(我有两个文件: '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*'
以下是script.sh中的 'for' 循环块
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.txt 和 input .txt
Note: I want to cat both files input1.txt and input.txt
推荐答案
通过重置$IFS
,可以禁用分词功能,因为分词功能会导致$1
中的模式扩展被视为单独的文件名.这是以 right 方式执行此操作的另一个原因.但是首先,假设您确实要向脚本传递一个模式,而不是仅使用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.txt
和input b.txt
,$1
将扩展为 4 个单词input
,a.txt
,input
和b.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屋!