Text Processing in Linux

shunmare

shun

Posted on August 12, 2023

Text Processing in Linux

Searching within Text

  • grep: Search for a pattern within files.

    • -i: Ignore case.
    • -r or -R: Recursively search in directories.
    • -v: Invert the search (return lines that don't match).
    $ grep "search_term" file.txt
    This line contains the search_term.
    
```bash
$ grep -i "Search_Term" file.txt
This line contains the search_term.
```
Enter fullscreen mode Exit fullscreen mode

Filtering and Transforming Text

  • awk: A versatile programming language for working on files.
  $ echo -e "a 1\nb 2\nc 3" | awk '{print $2}'
  1
  2
  3
Enter fullscreen mode Exit fullscreen mode
  • sed: Stream editor for filtering and transforming text.
  $ echo "Hello World" | sed 's/World/Universe/'
  Hello Universe
Enter fullscreen mode Exit fullscreen mode

Sorting and Counting

  • sort: Sort lines in text files.

    • -r: Reverse the result of comparisons (descending).
    • -n: Compare according to string numerical value.
    $ echo -e "banana\napple\ncherry" | sort
    apple
    banana
    cherry
    
  • uniq: Report or omit repeated lines.

    • -c: Prefix lines by the number of occurrences.
    $ echo -e "a\na\nb\nb\nb\nc" | uniq -c
      2 a
      3 b
      1 c
    

wc: Count words, lines, and characters in files.
- -l: Count lines.
- -w: Count words.
- -c: Count bytes.

  ```bash
  $ echo "Hello World" | wc -w
  2
  ```
Enter fullscreen mode Exit fullscreen mode

Text Display

  • cat: Concatenate and display the content of files.
  $ cat file.txt
  This is the content of file.txt.
Enter fullscreen mode Exit fullscreen mode
  • tac: Display files in reverse.
  $ echo -e "line1\nline2\nline3" | tac
  line3
  line2
  line1
Enter fullscreen mode Exit fullscreen mode
  • nl: Number lines of files.
  $ echo -e "line1\nline2\nline3" | nl
  1  line1
  2  line2
  3  line3
Enter fullscreen mode Exit fullscreen mode
  • head: Display the beginning of a file.

    • -n: Specify the number of lines to show.
      $ echo -e "line1\nline2\nline3" | head -n 2
      line1
      line2
    
  • tail: Display the end of a file.

    • -n: Specify the number of lines to show.
    • -f: Follow the content of a file in real-time.
      $ echo -e "line1\nline2\nline3" | tail -n 2
      line2
      line3
    
💖 💪 🙅 🚩
shunmare
shun

Posted on August 12, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related