Basic Linux Tutorial
Introduction – What is it? Why to learn? Linux installation directory structures Boot process Run levels in Linux Desktop Environments Different shells BASH Internal and External Commands Basic Linux Commands Important files and directories in Linux Environmental and Shell Variables Command history in Linux Character classes in Linux Text editors vim nano Searching files Creating new files Viewing File Contents File commands File permissions and ownership WildCards (Globbing) in files File compression Directory commands xargs command in Linux Comparing files Searching patterns using grep command Translating the characters using tr command Extracting data using cut command Stream editing using sed command Data extraction and reporting using awk command Sorting the file or string input uniq command in Linux Difference between grep, tr, cut, sed and awk commands Hardware commands Hard disk and memory space commands Working with Processes Managing Jobs Working with cron jobs Service command in Linux Network commands Managing Users and Groups Other Popular commands Standard streams and Redirection Pipes Package Managers in LinuxData extraction using awk in linux shell
awk is a very powerful tool in Linux. awk allows you to do all things that can be done using grep, sed commands. awk assumes the file as a database table. Each line is considered as a row and columns are separated by space. By default, space is used as a delimiter seperating columns. but you can mention different delimiter (field separator) by using FS option. Value in the first column can be accessed using $1, Value in the second column can be accessed using $2 and so on. Entire line (record) can be accessed using $0. Below examples will help you understand how it work.
awk ‘BEGIN{FS=”:”} {print $1}’ f1.txt
# This command will print first column from the file f1.txt. Note that we have specified “:” as the field separator.
awk ‘BEGIN{FS=”:”} $1==’abc’ {print $0}’ f1.txt
# This command will print only those lines from f1.txt where the value of first column is “abc”
awk ‘BEGIN{FS=”:”} $1!=’abc’ {print $0}’ f1.txt
# This command will print only those lines from f1.txt where the value of first column is not “abc”
awk ‘/abc/{print $1}’ f1.txt
# This command will print the first column from the file f1.txt where that lines matches the pattern “abc”. Note that
# you can give the regular expressions in the pattern.
awk ‘!/abc/{print $1}’ f1.txt
# This command will print the first column from the file f1.txt where lines do not match the pattern “abc”.
awk ‘NR==7,NR==9’ f1.txt
# This command will print lines 7 and 9 from file f1.txt
Replacing the text using awk command
You can use below syntax to replace the pattern using awk.
$ awk ‘{gsub(/pattern/,”replacement”)}’ <file-name>
Web development and Automation testing
solutions delivered!!