How To Linux Bash For Loop In Files?

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/linux-bash-loop-files/
PINTEREST
PINTEREST
INSTAGRAM

Bash provides a lot of useful programming functionalities. for loop is one of the most useful of them. We can use for loop for iterative jobs. Linux system administrators generally uses for loop to iterate over files and folder. In this tutorial we will look how to use for loop to iterate over files and directories in Linux. This examples can be used any of Linux distribution which uses bash as shell like Ubuntu, CentOS, RedHAT, Fedora, Debian, Kali, Mint etc. This mechanism is named as for each some programming languages where a list is iterated over.

Syntax

Syntax offor look is like below.

Here for will loop over ITEM1, ITEM2, etc. and run CODE in every step and use F

Loop Over Given File Names

The simplest usage for for loop is over given file names. We will provide the file files by separating them with spaces. In this example we will provide file names a , b and c and then print them with some string.

Loop Over Given File Names

Loop Over Given File Names

Loop Over Listed File Names

What can we do if there is thousand of files to be loop in a directory. We need more dynamic way to provide file names. We can use ls command in order to provide file names as a list without typing one by one.

LEARN MORE  How To Check Whether A File Exists Using Python?

Loop Over Listed File Names

Loop Over Listed File Names

Loop Over Specified File Extensions

Some times we may need to work on specific file extensions. We can specify the file extension we want to loop with for loop. In this example we will print encoding types of files with *.txt extension.

Loop Over Specified File Extensions

Loop Over Specified File Extensions

Loop Over Files Reading From Text File

Files names can be stored in a text file line by line. We can read file names from specified text file and use in a for loop. In this example we will read following text file and loop over lines. Our file name is filenames.txt

Loop Over Files Reading From Text File

Loop Over Files Reading From Text File

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/linux-bash-loop-files/
PINTEREST
PINTEREST
INSTAGRAM

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)