Wednesday, February 7, 2018

Useful Linux/Unix commands


Below command can be used for a scenario where grep command returns the searching string.

$  grep -H "some text " * | awk -F: '{print $1 }' | wc -l

-H  => as per the Linux man page, displays the file name.
some text => is the text that needs to be searched, double quotes used since there is space between the search string.
* => represents all the files in that folder or where the $ pwd command display value.

-F: => delimits using ":" on the output of grep command.

wc -l => word comm
grep output

file.txt:<some text ....

output of command  < grep -H "some text " * | awk -F: '{print $1 }' >
file.txt

----------------------------------------------

Below command can be used for a scenario where you need to move the files in the directory (Linux) to different location

$ for i in `ls -ltr | grep Jan | awk '{print $9}' `; do mv $i* ../to_delete/; done
Use: ls - lrt command, output is as follows

       -rw-rw-r--. 1 user1 root 2356 Jan  7 12:25 file.xml
       -rw-rw-r--. 1 user1 root 2356 Feb  7 12:25 file.xml

grep Jan => <month> Ls command output format will filter the first record in the above sample.

when delimited with space, the file name is on 9 th position.
awk '{print $9} => provides the file name.

mv $i is the index of the for loop, which is the file name actually.

---------------------------------------------
Below command can be used to print the size of the file in Megabits or Kilobits

$ ls -lr --block-size=M
$ ls -lhS
-h => human readable size format
-S => sort the size

refer man ls page for more details

--------------------------------------------

No comments:

Post a Comment