Reading complete line in 'for' loop with spaces, tabs with multiple input files

拈花ヽ惹草 提交于 2019-12-20 04:56:17

问题


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'

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 command:

bash script.sh 'input*'

Below is 'for' loop block in script.sh

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

I got following error on execution:

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

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


回答1:


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

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*

and in your script:

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


来源:https://stackoverflow.com/questions/35774850/reading-complete-line-in-for-loop-with-spaces-tabs-with-multiple-input-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!