Bash 파일 읽기

Bash, or the Bourne Again SHell, is the default command-line interpreter for Linux and other Unix-like operating systems. It is a powerful tool for automating tasks and managing files. In this blog post, we will explore various ways to read a file in Bash.

Method 1: Using the cat command

The cat command is commonly used to display the contents of a file. To read a file using cat, you can simply run the following command:

cat filename.txt

Replace filename.txt with the name of the file you want to read.

Method 2: Using the less command

The less command is a pager program that allows you to view files one page at a time. It is useful for reading large files or files that require scrolling. To read a file using less, use the following syntax:

less filename.txt

Once less is open, you can navigate through the file using the arrow keys. Press q to exit less when you’re done reading.

Method 3: Using the head or tail command

If you only want to read a certain number of lines from the beginning or the end of a file, you can use the head or tail command, respectively. Here are the commands to read the first few lines or the last few lines of a file:

To read the first 10 lines of a file:

head -n 10 filename.txt

To read the last 10 lines of a file:

tail -n 10 filename.txt

Replace 10 with the desired number of lines.

Method 4: Using input/output redirection

Another way to read a file is by using input/output redirection. You can redirect the contents of a file to the standard input of a command or save the output of a command to a file. To read a file using input redirection, use the following syntax:

command < filename.txt

Replace command with the appropriate command to process the file.

To save the output of a command to a file, use output redirection:

command > output.txt

Replace command with the appropriate command, and output.txt with the desired filename.

Conclusion

Reading files in Bash is a common task, and there are multiple ways to achieve it. Whether you choose to use the cat, less, head, tail, or input/output redirection method depends on your specific requirements. Experiment with these methods to find the one that works best for you. Happy file reading in Bash!