Question
Say I have this file:
- data.txt
- hello
- world
- hello world
- test.sh
- #!/bin/bash
- for i in $(cat $1); do
- echo "tester: $i"
- done
I'd like to have the for iterate over each line individually ignoring whitespaces though, i.e. the last two lines should be replaced by:
How-To
With for and IFS (internal field separator):
- #!/bin/bash
- IFS=$'\n' # Make newline the only separator
- set -f # Disable globbing
- for i in $(cat "$1"); do
- echo "tester: $i"
- done
Or with read (no more cat):
- #!/bin/bash
- while IFS= read -r line; do
- echo "tester: $line"
- done < "$1"
* What is IFS in context of for looping?
* Linux tip: Using the read command
沒有留言:
張貼留言