2021年3月27日 星期六

[Linux 常見問題] Bash - How to process each output line in a loop?

 Source From Here

Question
I have a number of lines retrieved from a file after running the grep command as follows:
  1. var=`grep xyz abc.txt`  
Let’s say I got 10 lines which consists of xyz as a result.

Now I need to process each line I got as a result of the grep command. How do I proceed with this?

HowTo
One of the easy ways is not to store the output in a variable, but directly iterate over it with a while/read loop. Something like:
test.sh
  1. #!/bin/sh  
  2. grep xyz abc.txt | while read -r line ; do  
  3.     echo "Processing $line"  
  4.     # your code goes here  
  5. done  
There are variations on this scheme depending on exactly what you're after. A sample usage:
root@localhost:demo_bash# cat abc.txt
xyz 123
test line1
456 xyz
test line2


root@localhost:demo_bash# ./test.sh
Processing xyz 123
Processing 456 xyz


沒有留言:

張貼留言

[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...