question about awk

given this:

[root@vblnxsrv02 setup]# ls -1 /dev/sd[b-z]
/dev/sdb
/dev/sdc
/dev/sdd
/dev/sde
/dev/sdf

returns a list of devices I want to use as input for some other operations. So ...

[root@vblnxsrv02 setup]# ls -1 /dev/sd[b-z] | awk '{FS="/"; print $3 }' 
 
sdc
sdd
sde
sdf
[root@vblnxsrv02 setup]#

Where I should get sdb, I get a blank line ... everything after is exactly what I want.

When this part is working, I plan to expand it a bit to

ls -1 /dev/sd[b-z] | awk '{FS="/"; print "some text " $3 " some more text" }' >> afile.lis

I'm open to either tweaking the above or an entirely different approach.

I've never used the awk notation you did, but for some reason it's separating oddly:

$ cat test| awk '{FS="/"; print $3}'

sdc
sdd
sde
sdf
$ cat test| awk '{FS="/"; print $2}'

dev
dev
dev
dev
$ cat test| awk '{FS="/"; print $1}'
/dev/sdb




That said, I normally use the -F flag for awk (Which does work):

$ cat test| awk -F'/' '{print $3}'
sdb
sdc
sdd
sde
sdf

Used cut instead of awk. Not sure why "awk" doesn't list the first one.
Maybe someone with superiour UNIX knowledge can help here.

ls /dev/sd[b-z] | cut -f3 -d "/" | awk '{print "some text" $1 "some other text" }'
1 Like

The problem is that you aren't setting the value of FS until _after_ the first record has already been read and split. That first line is being split on whitespace. Since there is none, $3 is empty.

You can use the -F/ option, or set FS in a BEGIN block, or set FS on the command line before the file is named:

awk -F/ '{ print $3 }'
awk 'BEGIN { FS="/" } { print $3 }'
awk '{ print $3 }' FS=/

Regards,
Alister

3 Likes

Aster007 - perfect. Thank you so much.