Reading complete line in 'for' loop with s

2019-03-01 10:47发布

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条回答
We Are One
2楼-- · 2019-03-01 11:28

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
查看更多
登录 后发表回答