Skip to main content

awk

# awk 
tee awk.txt <<-'EOF'
john wang male 30 02103213
ludc dasf fama 12 12311321
EOF

awk '{print $1,$4}' awk.txt
awk '{print NF}' awk.txt
# Print last line, awk defaults to space as separator, NF internal variable represents number of elements after division by separator
awk '{print $NF}' awk.txt
cat awk.txt | awk '{print substr($1,1)}'
cat awk.txt | awk '{print length}'

cat awk.txt | awk 'BEGIN{total=0}{total+=$4}END{print total}'
cat awk.txt | awk 'BEGIN{total=0}{total+=$4}END{print total/NR}'

sed

tee sed.txt <<-'EOF'  
this is line 1, this is First line
this is line 2, the Second line, Empty line followed

this is line 4, this is Third line
this is line 5, this is Fifth line
EOF
# Replace
sed 's/this/That/g ; s/line/LINE/g' sed.txt
# Delete first line
sed '1d' sed.txt
# Save file after deletion
sed '1d' sed.txt > save_file
# If want to modify source file directly
sed -i '1d' save_file

# Delete specified range (lines 1-3)
sed '1,3d' sed.txt

# Delete last line
sed '$d' sed.txt

# Empty file
sed '1,$d' sed.txt

# Keep only 5th line
sed '5!d' sed.txt

# Delete all lines containing Empty
sed '/Empty/d' sed.txt

# Delete empty lines
sed '/^$/d' sed.txt

# Replace first value of each line
sed 's/line/LINE' sed.txt

sed 's/line/LINE/2' sed.txt
sed 's/line/LINE/g' sed.txt

# Replace this at beginning with that
sed 's/^this/that/'
Agreement
The code part of this work is licensed under Apache License 2.0 . You may freely modify and redistribute the code, and use it for commercial purposes, provided that you comply with the license. However, you are required to:
  • Attribution: Retain the original author's signature and code source information in the original and derivative code.
  • Preserve License: Retain the Apache 2.0 license file in the original and derivative code.
The documentation part of this work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License . You may freely share, including copying and distributing this work in any medium or format, and freely adapt, remix, transform, and build upon the material. However, you are required to:
  • Attribution: Give appropriate credit, provide a link to the license, and indicate if changes were made.
  • NonCommercial: You may not use the material for commercial purposes. For commercial use, please contact the author.
  • ShareAlike: If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.