Home‎ > ‎

sed/awk

(It's not so bad...)


sed



awk


data from columns delimited by whitespace and with specific match

if the directory is such: 
cmercier@Balsa ~/ $ ls -la
total 112
drwxr-xr-x  11 cmercier  staff   352B Sep 24 11:21 ./
drwxr-xr-x   6 cmercier  staff   192B May 24 22:58 ../
-rw-r--r--@  1 cmercier  staff   6.0K Sep 24 11:21 .DS_Store
-rw-r--r--   1 cmercier  staff   3.4K Jun 29 11:31 CFG_DB01_install.sh
-rwxr-xr-x@  1 cmercier  staff    11K May 18 11:17 postImagePreDeployCentOS7-2.sh*
-rwxr-xr-x@  1 cmercier  staff    12K May 24 16:27 postImagePreDeployCentOS7.sh*
-rwxr-xr-x@  1 cmercier  staff   1.6K Sep 17 09:59 pushIptablesChanges.sh*
-rwxr-xr-x@  1 cmercier  staff   1.4K May 18 11:28 pushToAllProd.sh*
-rwxr-xr-x@  1 cmercier  staff   361B May 18 11:28 updateHosts.sh*
-rwxr-xr-x@  1 cmercier  staff   2.5K Sep 24 11:20 updateIptables.sh*
-rwxr-xr-x@  1 cmercier  staff   3.5K May 18 11:26 updateNfsConfigs.sh*

output the first and last column, but only with including "update": 
cmercier@Balsa ~/ $ ls -la | awk '/update/ {print $1, $9;}'
-rwxr-xr-x@ updateHosts.sh*
-rwxr-xr-x@ updateIptables.sh*
-rwxr-xr-x@ updateNfsConfigs.sh*

Same thing, but here not the last (9th) column, but the second to last (8th) column: 
cmercier@Balsa ~/ $ ls -la | awk '/update/ {print $1, $8;}'
-rwxr-xr-x@ 11:28
-rwxr-xr-x@ 11:20
-rwxr-xr-x@ 11:26


Break a string by a defined delimiter, and print out the columns

View the entire hostname
[root@dude01 ~]# hostname
dude01.mb2.prod.chuck.com

separate the fqdn by ".", and output the 3rd word
[root@dude01 ~]# echo $HOSTNAME | awk -F. '{print $3}'
prod

separate the fqdn by ".", and output the 2nd word
[root@dude01 ~]# echo $HOSTNAME | awk -F. '{print $2}'
mb2

separate the fqdn by ".", and output the 1st AND 4th word:
[root@dude01 ~]# echo $HOSTNAME | awk -F. '{print $1} {print $4}'
dude01
chuck

Sending awk output to variables, not console

if you want to use awk in a script, and want the output to be assigned to a variable use the var=$() syntax
[root@dude01 ~]# foo=$(echo $HOSTNAME | awk -F. '{print $1} {print $4}')
[root@dude01 ~]# echo $foo
dude01 chuck


References



Comments