Print nth line from file
sed 'Nq;d' file.txtPrepend text to beginning of file
echo "new content" | cat - file.txt > temp
mv temp file.txtsed -i '1s/^/new content\n/' file.txtRemove lines containing only whitespace
sed -i '/^\s*$/d' file.txtDelete nth line from file
# N should be the target line number
sed -i 'Nd' file.txtReplace an entire line in file by line number
# N should be the target line number
sed -i 'Ns/.*/replacement-line/' file.txtHeredoc
cat << EOF > file.txt
The current working directory is $PWD.
You are logged in as $(whoami).
EOFPlain-print the difference between two files
Suppose we have two files: packages.fedora and packages.
packages.fedora:
autossh
bash-completion
bat
bc
borgmatic
bzip2
cmake
curl
diff-so-fancy
diffutils
dnf-plugins-corepackages:
bash-completion
bc
bzip2
curl
diffutils
dnf-plugins-coreTo plain-print the lines that exist in packages.fedora but do not exist in packages:
comm -23 <(sort packages.fedora) <(sort packages)Output:
autossh
bat
borgmatic
cmake
diff-so-fancy- The
commcommand compares two sorted files line by line. - The
-23flag is shorthand for-2and-3. -2suppresses column 2 (lines unique topackages).-3suppresses column 3 (lines that appear in both files).
Split large text file into smaller files with equal number of lines
split -l 60 bigfile.txt prefix-Loop through lines of file
while read line; do
echo "$line";
done </path/to/file.txtUse grep to find URLs from HTML file
cat urls.html | grep -Eo "(http|https)://[a-zA-Z0-9./?=_%:-]*"Use Awk to print the first line of ps aux output followed by each grepped line
To find all cron processes with ps aux:
ps aux | awk 'NR<2{print $0;next}{print $0 | grep "cron"}' | grep -v "awk"