Reprinted -- how to read a file in one row

Source: Internet
Author: User

Original article address:

 

There are many methods to read files using bash scripts. Please refer to the first part. I used the while loop and the pipeline command (|) (cat $ file | while read line; do... ), And increment the I value in the loop. Finally, I get the I that is not what I think. The main reason is that the pipeline command will initiate a sub-shell to read the file, and any operations in the (sub-shell) while loop (such as I ++ ), will be lost with the completion of the sub-shell.

The second is the worst. The most obvious error is that the For Loop (for fileline in $ (cat $ file) is used during file reading ); do ..), in this way, the row is changed every time a word is printed, because the for loop uses spaces as the default ifs.

The perfect method is the third while loop (While read line; do .... Done <$ File) Is the most suitable and simple method for reading files in one row. See the following example.

Input: $ cat sample.txt This is sample fileThis is normal text file Source: $ cat readfile.sh #!/bin/bash i=1;FILE=sample.txt # Wrong way to read the file.# This may cause problem, check the value of ‘i‘ at the end of the loopecho "###############################"cat $FILE | while read line; do        echo "Line # $i: $line"        ((i++))doneecho "Total number of lines in file: $i" # The worst way to read file.echo "###############################"for fileline in $(cat $FILE);do        echo $fileline done # This is correct way to read file.echo "################################"k=1while read line;do        echo "Line # $k: $line"        ((k++))done < $FILEecho "Total number of lines in file: $k" Output: $ ./readfile.sh ###############################Line # 1: This is sample fileLine # 2: This is normal text fileTotal number of lines in file: 1###############################ThisissamplefileThisisnormaltextfile################################Line # 1: This is sample fileLine # 2: This is normal text fileTotal number of lines in file: 3

 

 



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.