Linux Blog

Bash Scripting Techniques

Filed under: Shell Script Sundays — TheLinuxBlog.com at 10:20 pm on Sunday, May 18, 2008

Here are some techniques that you can use in your bash scripts for finding and searching through files. Combined with other shell scripting techniques these can be very powerful.

Find all files in the current directory and print them:

find . -iname ".jpg"

Find all files that you have access to read with matching patern:

find / -iname "pattern"

Normally with grep text is matched and is case sensitive. Heres how to do a case insensitive search with grep:

cat [filename] | grep -i [match]

Finding and replacing text is easily done in bash with sed. This find and replace puts the contents into a new file:

 cat [filename] | sed 's/FIND/REPLACE/' > [new filename]

Finding the line number that a particular line of text is on is sometimes useful. Here is how to do it:

 cat [filename] | grep -n [match]

Looping over a file in bash and echoing the output is sometimes useful for the processing of text files. Heres how to do it:

cat [filename] | while read i; do echo $i; done

Thats about all the bash scripting techniques that I can currently think of for finding in files. I know there are a ton more that I use but its hard to write them all down at once. As I come up with them or solve a problem I’ll add them here. If you have any of your own, please leave them in the comments.