Some useful bash hacks

Useful Bash Hacks

So, listed below are some of my favorite bash commands that I use very frequently.

1) Move all files of a particular type in a directory

The command below searches for all the zip files in a particular directory hierarchy and moves it to a new directory. The depth of the search can be adjusted with the maxdepth option for the find command. I often use this to clean up my Desktop.

find ./ -name “*.zip” -exec mv {} ./zipped_files    \;

For all files in a the current directory and to ignore sub-directories  –

find ./ -name “*.zip” -maxdepth 1 exec mv {} ./zipped_files    \;

2) Modify each line in a text file

The sed command is pretty useful for all kinds of stream editing. Lets say I want to surround each line in a file with a html tag. This can be easily done via the sed command. Lets say I want enclose an XML tag for each line in a text file, sed makes this pretty easy.

Input File


1

2

3

4

The command which I am going to use is


sed 's:.*:<id>&</id> sample.txt > new_file.txt

And the output file would be


<id>1</id>
<id>2</id>
<id>3</id>
<id>4</id>

3) Cut command Example

Again, this is a pretty common hack. List all users in the system along with their home directories


cut -d : -f 1,6 /etc/passwd


Advertisements