Announcement

Collapse
No announcement yet.

Odd extra space, comma, and line feed in bash awk output?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    [SOLVED] Odd extra space, comma, and line feed in bash awk output?

    I'm try to write a small bash command to put in ~/.bashrc on a server to identify reagion and city location from the IP address. I am using a program called "ip2locationio" and the command for this is:
    Code:
    ip2locationio -f region_name,city_name -o pretty
    which outputs like this:
    Code:
    region_name,city_name
    "New Jersey","Jersey City"​
    The output I want is:
    Code:
    New Jersey, Jersey City​
    so I'm piping the output through awk like this:
    Code:
    ip2locationio -f region_name,city_name -o pretty | awk -F'"' '{print $2,",", $4}'

    but for some reason I can't glean I'm getting:
    Code:
     ,
    New Jersey , Jersey City

    How do I eliminate that first line?
    Last edited by oshunluvr; Jun 06, 2024, 10:36 AM.

    Please Read Me

    #2
    OK, I got rid of the leading space in the first line by changing to this:
    Code:
    |awk -F'"' '{print $2",", $4}'
    Honestly I can live with the extra line feed but I'd like to eliminate the extra comma.
    Last edited by oshunluvr; Jun 06, 2024, 10:36 AM.

    Please Read Me

    Comment


      #3
      The extra line must come from the fact that the ip2locationio output is two lines. So I trimmed it with tail and now this:
      Code:
      ip2locationio -f region_name,city_name -o pretty |tail -n 1 |awk -F'"' '{print $2",", $4}'
      ​gets me this:
      Code:
      New Jersey, Jersey City
      Success!

      Still not sure this would work if the place names had one or three or more "words" in them.
      Last edited by oshunluvr; Jun 06, 2024, 10:41 AM.

      Please Read Me

      Comment


        #4
        I tested it on another IP ans it seems to work:
        Code:
        North Carolina, Greenville

        Please Read Me

        Comment


          #5
          Generally, awk first uses a pattern to select the lines, awk 'pattern {code}'. It's very like grep, except that grep just prints the matches, awk wants regexes delimited by /, and awk allows expressions as well.

          A pattern to select line 2 is NR==2.

          Often a regex pattern is more robust, say /^"/.
          Regards, John Little

          Comment

          Working...
          X