Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Several common methods for shell to read files by line

Shulou Source: shulou.com Published: 2022-06-03 03:15:18 09月29日 Update

1. By redirecting the + read command

While read linedo # Operation on each line of string shell_commandsdone < File.txt

two。 Redefine through cat + IFS

IFS_old=$IFSIFS=$'\ n'for line in $(cat File.txt) do shell_commandsdoneIFS=$IFS_old

3. Pipe + read command (often seen, but not easy to use. )

Cat File.txt | read linedo shell_commandsdone

Note: this approach has a very obvious flaw. Variables defined by shell_command will "fail" at the end of the loop!

For example:

The file1.txt is as follows:

Abcd

The shell code for method 1:

# number of lines line_count=0# file contents file_content= "# start reading while read linedo echo" I read: "echo ${line} line_count=$ (expr $line_count + 1) echo" this is the ${line_count} line "file_content=" $file_content $line "done"

Tags: Content files methods results code commands programs this is check obvious one line bad practices variables characters strings pipes defects loops run Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Shulou Tech Info OPPO Reno MariaDB Shulou Information