Skip to content

Latest commit

 

History

History
143 lines (120 loc) · 3.1 KB

03.filter.search.files.contents.md

File metadata and controls

143 lines (120 loc) · 3.1 KB

Basic

Search file content with grep

grep is a command used to search files' contents.

Search lines that contains the string when in the file Documents/file.txt :
image

Print lines numbers :
image

Ignore case (uppercase, lowercase) when searching :
image

Reverse search (search lines that don't contain the string char) :
image

Search the exact word char in the file Documents/file.txt :
image

Search recursively in the directory Documents/ all files that contains the string char :
image

Sort file content using sort

sort is a command used to sort file content.

Print file content sorted alphabetically :

user@ubuntu:~$ cat Documents/file2.txt 
Oh my god
Bullshit
One two three
This is a test
One two three
This is a test
user@ubuntu:~$ sort Documents/file2.txt 
Bullshit
Oh my god
One two three
One two three
This is a test
This is a test

Write sorted content to another file :

user@ubuntu:~$ sort Documents/file2.txt -o Documents/file2_sorted.txt

Print file content sorted in reverse order:

user@ubuntu:~$ sort -r Documents/file2.txt                             
This is a test
This is a test
One two three
One two three
Oh my god
Bullshit

Print file content sorted numerically:

user@ubuntu:~$ cat Documents/numbers.txt 
03
4
2
01
user@ubuntu:~$ sort -n Documents/numbers.txt 
01
2
03
4

Detect duplicate lines using uniq

uniq is used to find repeated lines in a file.

Print file content without duplicate lines:

user@ubuntu:~$ cat Documents/file2_sorted.txt 
Bullshit
Oh my god
One two three
One two three
This is a test
This is a test
user@ubuntu:~$ uniq Documents/file2_sorted.txt 
Bullshit
Oh my god
One two three
This is a test

Write file content without duplicates to another file:

user@ubuntu:~$ uniq Documents/file2_sorted.txt  Documents/file2_sorted_uniq.txt

Prefix lines by the number of occurrences:

user@ubuntu:~$ uniq -c Documents/file2_sorted.txt
      1 Bullshit
      1 Oh my god
      2 One two three
      2 This is a test

Only print duplicate lines:

user@ubuntu:~$ uniq -d Documents/file2_sorted.txt
One two three
This is a test

Count lines/words/chars using wc

Count number of lines in a file:

user@ubuntu:~$ wc -l Documents/file2.txt 
6 Documents/file2.txt

-l can be replaced with -w to count number of words, or -m to count number of characters.

If we want to count everything at once, we can use the command wc without a parameter:

user@ubuntu:~$ wc Documents/file2.txt
 6 18 77 Documents/file2.txt