程式扎記: [Linux 常見問題] Bash - How to loop over the lines of a file?

標籤

2015年10月15日 星期四

[Linux 常見問題] Bash - How to loop over the lines of a file?

Source From Here 
Question 
Say I have this file: 
- data.txt 
  1. hello  
  2. world  
  3. hello world  
This program: 
- test.sh 
  1. #!/bin/bash  
  2.   
  3. for i in $(cat $1); do  
  4.     echo "tester: $i"  
  5. done  
Execution result: 
# ./test.sh data.txt
tester: hello
tester: world
tester: hello
tester: world

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: 
tester: hello world

How-To 
With for and IFS (internal field separator): 
  1. #!/bin/bash  
  2. IFS=$'\n'     # Make newline the only separator  
  3. set -f              # Disable globbing  
  4. for i in $(cat "$1"); do  
  5.     echo "tester: $i"  
  6. done  
# echo "$IFS" | cat -vte // Original IFS includes "\t", " " and "\n"
^I$
$

# ./test.sh data.txt
tester: hello
tester: world
tester: hello world

Or with read (no more cat): 
  1. #!/bin/bash  
  2.   
  3. while IFS= read -r line; do  
  4.   echo "tester: $line"  
  5. done < "$1"  
Supplement 
What is IFS in context of for looping? 
Linux tip: Using the read command

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!