Wednesday, October 4, 2017

HowTo: Move A Folder In Linux Using mv Command

How do I move a folder in BSD/Linux/Apple OX or Unix operating system using bash command line option?

You need to use the mv command to move folder, files, and directories in Linux terminal. The syntax is as follows:

mv source target
mv folder1 folder2 target
mv folder1 file1 target
mv -option source target

The following example would move a folder named documents, without changing its name, from the current directory to an existing subdirectory of the current directory named /backups:
mv documents /backups
mv command can be used to move any number of files and folders in a single command. In this example, the following command moves all folders, including all the contents of those directories, from the current directory to the directory called /nas03/users/home/v/vivek
mv * /nas03/users/home/v/vivek
Please note that the asterisk is a wildcard character that represents all files and folders the current directory. In this next example, move only foo and bar folders from the /home/tom directory to the directory called /home/jerry:
mv /home/tom/foo /home/tom/bar /home/jerry
OR
cd /home/tom
mv foo bar /home/jerry
mv can see explain what is being done with the -v option i.e. it shows the name of each file before moving it:
mv -v /home/tom/foo /home/tom/bar /home/jerry
Sample outputs:
`/home/tom/foo/' -> `/home/jerry/foo'
`/home/tom/bar/' -> `/home/jerry/bar'
You can prompt before overwrite i.e. pass the -i option to make mv interactive if the same name files/folder already exists in the destination directory:
mv -i foo /tmp
Sample outputs:
mv: overwrite `/tmp/foo'? 

Other options

Taken from the man page of gnu/mv command:

What is the correct way to completely remove an application?

  • apt-get remove packagename
    will remove the binaries, but not the configuration or data files of the package packagename. It will also leave dependencies installed with it on installation time untouched.
  • apt-get purge packagename or apt-get remove --purge packagename
    will remove about everything regarding the package packagename, but not the dependencies installed with it on installation. Both commands are equivalent.
    Particularly useful when you want to 'start all over' with an application because you messed up the configuration. However, it does not remove configuration or data files residing in users home directories, usually in hidden folders there. There is no easy way to get those removed as well.
  • apt-get autoremove
    removes orphaned packages, i.e. installed packages that used to be installed as an dependency, but aren't any longer. Use this after removing a package which had installed dependencies you're no longer interested in.
  • aptitude remove packagename or aptitude purge packagename (likewise)
    will also attempt to remove other packages which were required by packagename on but are not required by any remaining packages. Note that aptitude only remembers dependency information for packages that it has installed.
And many more exist. Lower-level dpkg-commands can be used (advanced), or GUI tools like Muon, Synaptic, Software Center, etc. There's no single 'correct way' of removing applications or performing other tasks interacting with your package management.
The list you found are just examples. Make sure you understand the meanings and try out what it wants to do before accepting the action (you need to press Y before it actually performs the actions as proposed).
The asterisk version in the question is probably wrong; apt-get accepts a regular expression and not a cầu pattern as the shell. So what happens with
sudo apt-get remove application*
is the following:
  1. The shell tries to expand application* looking at the files in the current directory. If (as is normally the case) it finds nothing, it returns the glob pattern unaltered (supposing bash with default behavior here --- zsh will error out).
  2. apt-get will remove the packages whose name contains a string that satisfies the regular expression application*, that is, applicatio followed by an arbitrary number of n: applicatio, application, applicationn, libapplicatio, etc.
  3. To see how this can be dangerous, try (without root for double safety) apt-get -s remove "wine*" (-s will simulate the thing instead of doing it) --- it will say is going to remove all packages that has "win" in their name and the dependant, almost the entire system...
Probably, the command that was meant is really
 sudo apt-get remove "^application.*"
(note the quotes and the dot) which will remove all packages whose name starts with application.
These commands,
sudo updatedb                  # <-- updates the locate database (index). harmless
sudo locate application        # <-- locates the file 'application'. harmless
sudo rm -rf (file/folder name) # <-- removes files/dirs recursively. dangerous.
are completely outside the scope of the package management. Do not remove files belonging to packages without using the package manager! It will get confused and is the wrong way to do things.
If you don't know to which package a file belongs, try this:
dpkg -S /path/to/file

List all file and foler linux

ls -Rla /

Tuesday, October 3, 2017

Editing files with vi

The thing you have to understand about vi and its work-alike editors is modality. Most programs have just one mode, accepting input and placing it at the cursor. This is what you probably expect from a program. But vi has other modes. When you start vi, you’ll be in “Normal” mode, which is really command mode. When you are in Normal mode, whatever you type is considered not to be input, but commands that vi will try to execute.
This may sound a little crazy, but it is actually a very powerful way to edit documents. Even if you hate it, the ubiquity of vi means that you’re going to need to learn the basics, because sometimes you just have to use it. On the other hand, if you enjoy working at a command line, then you may end up loving vi.

Lesson 1: How to Quit vi

Since vi is the default editor, there’s a good chance you got dropped into it without knowing it. This can be extremely frustrating if you don’t know your way around the program.
To exit vi without saving changes, hit Escape a couple of times to ensure you are in Normal mode, and then type:
:q!

Lesson 2: Editing with vi

Start vi and press i. The cursor may change shape, and INSERT is displayed at the bottom of the screen (in most vi clones). You are now in insert mode — all your keystrokes are entered into the current buffer and are displayed to the screen.
Hit the Escape key. The cursor changes shape again, and INSERT has disappeared. You are back in Normal mode. Hitting Escape a few times will pretty much always cancel whatever you are doing and return you to Normal mode.
Command mode is also where you move around in the file. On most systems, you can use the arrow keys to move the cursor. If that fails, cursor movement can be accomplished with the hjkl keys:
h   move left one character
j   move down one character
k   move up one character
l   move right one character
vi has its own command line, which you access by typing a colon. Commands typed at the command line will not be executed until you hit Enter, just like in the shell.
Many of the commands that you will use in command mode begin with a colon. For example, the command to quit is :q, as we learned in Lesson 1 above. Actually, in Lesson 1 we added !, which tells vi to “force” the operation. If you have edited the file, typing :q will not immediately exit the program, but instead produce this error message:
E37: No write since last change (add ! to override)
To save your changes, use the :w command (“Write”). You can save and quit all in one go by typing both commands together:
:wq
Of course, if you started vi without giving a file name, you’ll need to provide one. For example, to save your working file as test.txt, you would type:
:w test.txt
Try editing some text now.
  • Start vi
  • Hit i to go to Insert mode.
  • Type some text.
  • Hit Escape to return to Normal mode.
  • Type :w test.txt to save your work
  • Type :q to quit

vi Quick Reference

Movement

h, j, k, l
left, down, up, right
$
To the end of the line
^
To the beginning of the line
G
To the end of the file
:1
To the beginning of the file
:47
To line 47

Editing

dd
Remove a line
5dd
Removing five lines
r
Replace a character
x
Delete a character
5x
Delete 5 characters
u
Undo last action
J
Join current and next lines (Note the capital — hold the Shift key)

Saving and Quitting

:q
Quit
:q!
Quit without saving
:wq
Write and quit
:w
Write (without quitting)
:e!
Reload currently open file from disk
:w test.txt
Write buffer to file test.txt
:e test2.txt
Open file test2.txt

The head Command

The head command reads the first few lines of any text given to it as an input and writes them to standard output (which, by default, is the display screen).
head's basic syntax is:
head [options] [file(s)]
The square brackets indicate that the enclosed items are optional. By default, head returns the first ten lines of each file name that is provided to it.
For example, the following will display the first ten lines of the file named aardvark in the current directory (i.e., the directory in which the user is currently working):
head aardvark
If more than one input file is provided, head will return the first ten lines from each file, precede each set of lines by the name of the file and separate each set of lines by one vertical space. The following is an example of using head with two input files:
head aardvark armadillo
If it is desired to obtain some number of lines other than the default ten, the -n option can be used followed by an integer indicating the number of lines desired. For example, the above example could be modified to display the first 15 lines from each file:
head -n15 aardvark armadillo
-n is a very tolerant option. For example, it is not necessary for the integer to directly follow it without a space in between. Thus, the following command would produce the same result:
head -n   15 aardvark armadillo
In fact, the letter n does not even need to be used at all. Just the hyphen and the integer (with no intervening space) are sufficient to tell head how many lines to return. Thus, the following would produce the same result as the above commands:
head -15 aardvark armadillo
head can also return any desired number of bytes (i.e., a sequence of eight bits and usually long enough to represent a single character) from the start of each file rather than a desired number of lines. This is accomplished using the -c option followed by the number of bytes desired. For example, the following would display the first five bytes of each of the two files provided:
head -c 5 aardvark anteater
When head counts by bytes, it also includes the newline character, which is a non-printing (i.e, invisible) character that is designated by a backslash and the letter n (i.e., \n). Thus, for example, if there are three new, blank lines at the start of a file, they will be counted as three characters, along with the printing characters (i.e., characters that are visible on the monitor screen or on paper).
The number of bytes or lines can be followed by a multiplier suffix. That is, adding the letter b directly after the number of bytes multiplies it by 512, k multiplies it by 1024 and m multiplies it by 1048576. Thus, the following command would display the first five kilobytes of the file aardvark:
head -c5k aardvark
The -c option is less tolerant than the -n option. That is, there is no default number of bytes, and thus some integer must be supplied. Also, the letter c cannot be omitted as can the letter n, because in such case head would interpret the hyphen and integer combination as the -n option. Thus, for example, the following would produce an error message something like head: aardvark: invalid number of bytes:
head -c aardvark
If head is used without any options or arguments (i.e., file names), it will await input from the keyboard and will successively repeat (i.e., each line will appear twice) on the monitor screen each of the first ten lines typed on the keyboard. If it were desired to repeat some number of lines other than the default ten, then the -n option would be used followed by the integer representing that number of lines (although, again, it is not necessary to include the letter n), e.g.,
head -n3
As is the case with other command line (i.e., all-text mode) programs in Linux and other Unix-like operating systems, the output from head can redirected from the display monitor to a file or printer using the output redirection operator (which is represented by a rightward-pointing angular bracket). For example, the following would copy the first 12 lines of the file Yuriko to the file December:
head -n 12 Yuriko > December
If the file named December did not yet exist, the redirection operator would create it; if it already existed, the redirection operator would overwrite it. To avoid erasing data on an existing file, the append operator (which is represented by two consecutive rightward pointing angle brackets) could be used to add the output from head to the end of a file with that name if it already existed (or otherwise create a new file with that name), i.e.,
head -n 12 Yuriko >> December
The output from other commands can be sent via a pipe (represented by the vertical bar character) to head to use as its input. For example, the following sends the output from the ls command (which by default lists the names of the files and directories in the current directory) to head, which, in turn, displays the first ten lines of the output that it receives from ls:
ls | head
This output could easily be redirected, for example to the end of a file named file1 as follows:
ls | head >> file1
It could also be piped to one or more filters for additional processing. For example, the sort filter could be used with its -r option to sort the output in reverse alphabetic order prior to appending file1:
ls | head | sort -r >> file1
The -q (i.e., quiet) option causes head to not show the file name before each set of lines in its output and to eliminate the vertical space between each set of lines when there are multiple input sources. Its opposite, the -v (i.e., verbose) option, causes head to provide the file name even if there is just a single input file.
The tail command is similar to the head command except that it reads the final lines in files rather than the first lines.
As is the case with other commands on Unix-like operating systems, additional information can be obtained about head and tail by using the man and info commands to reference the built-in documentation, for example
man head
or
info tail

Linux tail command

About tail

tail outputs the last part, or "tail", of files.

Description

tail prints the last 10 lines of each FILE to standard output. With more than one FILE, it precedes each set of output with a header giving the file name. If no FILE is specified, or if FILE is specified as a dash ("-"), tail reads from standard input.

tail syntax

tail [OPTION]... [FILE]...

Options

In the options listed below, arguments that are mandatory for long options are mandatory for short options as well:
-c, --bytes=K Output the last K bytes; alternatively, use "-c +K" to output bytes starting with the Kth byte of each file.
-f, --follow[={name|descriptor}] Output appended data as the file grows; -f, --follow, and --follow=descriptor are equivalent. If name is specified, the file with filename name will be followed, regardless of its file descriptor.
-F Same as "--follow=name --retry".
-n, --lines=K Output the last K lines, instead of the default of the last 10; alternatively, use "-n +K" to output lines starting with the Kth.
--max-unchanged-stats=N With --follow=name, reopen a FILE which has not changed size after N (default 5) iterations to see if it has been unlink'ed or renamed (this is the usual case of rotated log files).
--pid=PID With -f, terminate operation after process ID PID dies.
-q, --quiet, --silent Never output headers giving file names.
--retry Keep trying to open a file even when it is, or becomes, inaccessible; useful when following by name, i.e., with --follow=name.
-s, --sleep-interval=N With -f, sleep for approximately N seconds (default 1.0) between iterations. With --pid=P, check process P at least once every N seconds.
-v, --verbose Always output headers giving file names.
--help Display a help message, and exit.
--version Display version information, and exit.

Notes

If the first character of K (the number of bytes or lines) is a "+", tail prints the beginning with the Kth item from the start of each file; otherwise, tail prints the last K items in the file. K may have a multiplier suffix: b (512), kB (1000), K (1024), MB (1000*1000), M (1024*1024), GB (1000*1000*1000), G (1024*1024*1024), and so on for T (terabyte), P (petabyte), E (exabyte), Z (zettabyte), Y (yottabyte).
With --follow (-f), tail defaults to following the file descriptor, which means that even if a tail'ed file is renamed, tail will continue to track its end. This default behavior is not desirable when you really want to track the actual name of the file, not the file descriptor (for example, in a log rotation). Use --follow=name in that case. That causes tail to track the named file in a way that accommodates renaming, removal and creation.

tail examples

tail myfile.txt
Outputs the last 10 lines of the file myfile.txt.
tail myfile.txt -n 100
Outputs the last 100 lines of the file myfile.txt.
tail -f myfile.txt
Outputs the last 10 lines of myfile.txt, and monitors myfile.txt for updates; tail then continues to output any new lines that are added to myfile.txt.
tail -f access.log | grep 24.10.160.10
This is a useful example of using tail and grep to selectively monitor a log file in real time.
In this command, tail monitors the file access.log. It pipes access.log's final ten lines, and any new lines added, to the grep utility. grep reads the output from tail, and outputs only those lines which contain the IP address 24.10.160.10.

Everything You Need To Know About The Less Command

In this guide, you will find out everything you need to know about the Linux "less" command.
The "less" command is considered to be a more powerful version of the "more" command which is used to display information to the terminal one page at a time.
Many of the switches are the same as the ones used with the more command but there are lots of extra ones available as well.
If you want to read through a large text file it is better to use the less command over an editor as it doesn't load the entire thing into memory.
It loads each page into memory a page at a time making it more efficient.

How To Use The Less Command

You can view any text file using the less command simply by typing the following into a terminal window:
less
If there are more lines in the file than space on the screen then a single colon (:) will appear at the bottom and you will have a number of options to move forward through the file.
The less command can also be used with output piped through another command.
For example:
ps -ef | less
The above command will show a list of running processes one page at a time.
You can press either the space bar or the "f" key to scroll forward.

Changing The Number Of Lines That Are Scrolled Through

By default, the less command will scroll a single page at a time.
You can change the number of lines that are scrolled when you press the space and "f" key by pressing the number immediately before pressing the key.
For example, enter "10" followed by either the space or "f" key will cause the screen to scroll by 10 lines.
To make this the default you can enter the number followed by the "z" key.
For example, enter "10" and then press "z". Now when you press the space or "f" key the screen will always scroll by 10 lines.A rather bizarre inclusion is the ability to press the escape key immediately prior to the space bar. The affect of this is to continue scrolling even when you have reached the end of the output.
To scroll one line at a time press either the "return" key, "e" or "j". You can change the default so that it scrolls a specified number of lines by entering a number before the specified keys. For example, enter "5" followed by the "e" key will make the screen scroll 5 lines every time "return", "e" or "j" are pressed. If you accidentally press an uppercase "J" the same result will occur except that if you hit the bottom of the output it will continue scrolling.
The "d" key allows you to scroll down a specified number of lines. Again by entering a number before "d" will change the default behavior so that it scrolls the number of lines you specify.
To scroll back up the list you can use the "b" key. Unlike the more command, this can work with both files and piped output. Entering a number before pressing the "b" key scrolls back up the specified number of lines. To make the "b" key permanently scroll by the specified number of lines enter the number you wish to use followed by the "w" key.
The "y" and "k" keys work similarly to the "b" and "w" keys except the default isn't to scroll one window at a time but one line at a time back up the screen.If you accidentally press uppercase "K" or uppercase "Y"  the result will be the same unless you hit the top of the output in which case the scrolling will continue beyond the beginning of the file.
The "u" key also scrolls back up the screen but the default is half the screen.
You can also scroll horizontally using the left and right arrow keys.
The right arrow scrolls half a screen to the right and the left arrow scrolls half a screen to the left. You can continue scrolling right over and over but you can only scroll left until you hit the beginning of the output.

Redisplay The Output

If you are viewing a log file or any other file that is constantly changing you might want to refresh the data.
You can use a lowercase "r" to repaint the screen or an uppercase "R" to repaint the screen discarding any output that has been buffered.
You can press an uppercase "F" to scroll forward. The benefit of using the "F" is that when the end of the file is reached it will keep trying. If a log is updating whilst you are using the less command any new entries will be displayed.

Move To A Specific Position In A File

If you want to go back to the beginning of the output press lowercase "g" and to go to the end press uppercase "G".
To go to a specific line enter a number before pressing the "g" or "G" keys.
You can move to a position which is a certain percentage through a file. Enter a number followed by the "p" or "%" key. You can even enter decimal points because let's face it, we all need to go to position "36.6%" through a file.

Marking Positions In A File

You can set a marker in a file using the "m" key followed by any other lowercase letter. You can then return to the marker by using the single quote "'" key followed by the same lowercase letter.
This means you can specify a number of different markers through the output which you can return to easily.

Searching For A Pattern

You can search for text within the output using the forward slash key followed by the text you wish to search or a regular expression.
For example /"hello world" will find "hello world".
If you want to search back up the file you have to replace the forward slash with a question mark.
For example ?"hello world" will find "hello world" previously output to the screen.

Load A New File Into The Output

If you have finished looking at a file you can load a new file into the less command by pressing the colon key (:) followed by the "e" or "E" key and the path to a file.
For example ":e myfile.txt".

How To Exit Less

To exit the less command press either the "q" or "Q" keys.

Useful Command Line Switches

The following run time switches may or may not be useful to you:
  • less -bN - The N stands for a number and loads the specified number of kilobytes into memory. By default, the value is 64 kilobytes but you can specify any number you wish. If you enter -1 then the entire file will be loaded into memory which may or may not be a good idea depending on the size of the file.
  • less -B - By default the less command allocates the required memory buffers by default when using piped output. You can use the -B switch to prevent auto buffering.
  • less -c or less -C - By default the screen repaints by scrolling up the screen. To clear the screen from the top down use the -c or -C switches.
  • less -e - Causes less to exit when it hits the end of the file for the second time
  • less -E - Causes less to exit when it hits the end of the file for the first time 
  • less -f - Open special files such as directories using less
  • less -F - Causes less to exit if a file is less than one screens worth of data
  • less - g - Only highlight the last item found when searching 
  • less -G - Suppress highlighting altogether when searching
  • less -hN - Specify the maximum number of lines the less command can scroll back
  • less -i - Ignore case when searching unless uppercase characters are found in the search pattern
  • less -I - Ignore case when searching
  • less -jN - The N stands for a number. This determines where on the screen a line is placed when searched for. For example searching for "hello world" will place the line found with "hello world" in it on line 1 if less -j1 is used.
  • less -J - This displays a little asterisk in the left column (status column) which shows when a piece of text which you have searched for has been found.
  • less -m - Displays the number of bytes through a file instead of a colon at the bottom of the screen
  • less -M - Displays the line numbers of the output. For example "lines 1-23"
  • less -n - Suppress line numbers
  • less -N - Display line numbers on each line
  • less -o - This is used with piped output only. It outputs each page of the piped output to the file one page at a time. If the file exists it will ask whether you want to overwrite it.
  • less -O - This is the same as -o except that it won't ask for confirmation before overwriting a file.
  • less -p - This starts less at the first occurrence of the pattern specified.
  • less -P "text" - This replaces the message at the bottom of the screen to the text specified
  • less -q - This prevents the bell from buzzing when you reach the end of the file. Other reasons for the bell to ring such an invalid key press remain.
  • less - Q - Suppresses all noises
  • less -s - This condenses blank lines. For example if a file has 4 consecutive blank lines and you use the less -s command only 1 blank line will be displayed.
  • less -S - This causes long lines to be truncated rather than wrap them onto the next line

Summary

There is much more to the less command than you would expect. You can read the full documentation by typing "man less" into a terminal window or by reading this manual page for less.
An alternative to less and more is the tail command which shows the last few lines of a file.