Find the answer to your Linux question:
Results 1 to 4 of 4
hi I got a text file and need to use awk command to print out various information from it. I've managed to print out all the variations less one. Anyone ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Nov 2012
    Posts
    21

    Using AWK commandto print out only the first fields that has 4 letters


    hi I got a text file and need to use awk command to print out various information from it.

    I've managed to print out all the variations less one. Anyone can help guide me how the command goes. The expected result is as follows.

    Example file containing:

    mark 10 20 30
    mike 10 20 30
    Johnny 10 20 30

    I want to use awk command and print out only the first field if it contains only 4 letters. Meaning the commands output should be:

    mark
    mike

    the closest I got to was with the following command:

    Code:
    awk '$1 ~ /[a-z][a-z][a-z][a-z]$/{print $1}' myfile.txt
    But it prints out all the fields in that line. Thanks for helping.

  2. #2
    Linux Newbie
    Join Date
    Jun 2012
    Location
    SF Bay area
    Posts
    164
    You can use "length($1)" to get the number of characters in the first field and use that to select records.

  3. #3
    Just Joined!
    Join Date
    Nov 2012
    Posts
    21
    Thank you. The following code works to print out first field of all those matching 4 characters.

    Code:
    awk 'length($1) ~ /4/{print $1}' copyme.txt

  4. #4
    Linux Newbie
    Join Date
    Jun 2012
    Location
    SF Bay area
    Posts
    164
    Quote Originally Posted by keshk View Post
    Thank you. The following code works to print out first field of all those matching 4 characters.

    Code:
    awk 'length($1) ~ /4/{print $1}' copyme.txt
    Glad it worked out. I'd probably use an arithmetic comparsion, meaning "length($1) == 4", but if you get the results you want another way that's all that matters.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •