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

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...