Files and Directories

Grep in Compressed Files

# -A lines to show after match
# -B lines to show before match
zgrep -A 50 -B 50 'command_status: 1281' files-*

# -E use regular expression in search
zgrep -E 'command_status: [1-9]' files-*

Who's Writing to a File

fatrace | grep file.log

List File Extensions, Recursively

find . -type f -printf "%f\n" | awk -F. 'NF > 1 && $NF != "" {print $NF}' | sort -u

Create Temporary File

AlmaLinux

$ mktemp
/tmp/tmp.UHHyLzjCB0

Ubuntu Linux

$ tempfile
/tmp/fileR5dt6r

Remove Windows Line Breaks

AlmaLinux

sudo dnf install -y dos2unix
dos2unix original.csv

Ubuntu Linux

sudo apt-get install -y dos2unix
dos2unix original.csv

Split a File in Small Pieces

split --verbose --bytes=<size> -d <file> <prefix>

Where:

  • --bytes=<size> is the maximum size of each piece, in bytes, or an integer followed by K, M, G, T, P, E, Z, Y
  • -d adds a numeric suffix in the end of the file name
  • <prefix> is the name of every piece

An example: an ISO file can be sliced in several 1GB files:

$ split --verbose --bytes=1G -d imagefile.iso img
creating file  "img00"
creating file "img01"
creating file "img02"
creating file "img03"
creating file "img04"

To join these files back together, use

cat img00 img01 img02 img03 img04 > imagem.iso

Listing Only One Column of a File

A file with columns separated by : can have its data displayed like this

cat file.log | cut -d":" -f4

Showing File Content, Removing Duplicates

cat file.log | awk '!a[$0]++'

List the Recursive Contents of a Directory

ls -R /my_path | awk '
/:$/&&f{s=$0;f=0}
/:$/&&!f{sub(/:$/,"");s=$0;f=1;next}
NF&&f{ print s"/"$0 }'

Besides showing the contents recursively, this command also shows the full path of the files, not just the names.

Reference: AskUbuntu.com

Get a File's MIME Type

file --mime-type -b my_file

Find a File by Content

grep -lr "text to fine" *.txt