简体   繁体   中英

Sed to add each match to own line

I have this

awk -F=":" -v RS="," '$1~/"name"/ {print}' | sed -e 's/^.*"name"[ ]*:[ ]*"//' -e 's/".*//'`

user1 user2 user3 user4 user5

I am trying to add a way of creating each match on its own line instead of side by side

user1
user2 
user3 
user4 
user5

For a bonus, is there a way of telling the awk and sed to skip the first match of "name"?

This is the output from the api

{
  "name": "users",
  "self": "http://",
  "users": {
    "size": 5,
    "items": [
      {
        "self": "http://",
        "name": "admin",
        "emailAddress": "admin@example.com",
        "avatarUrls": {

        },
        "displayName": "admin",
        "active": true
      },
      {
        "self": "http://",
        "name": "user1",
        "emailAddress": "user1@example.com",
        "avatarUrls": {

        },
        "displayName": "user1",
        "active": true
      },
      {
        "self": "http://",
        "name": "user2",
        "emailAddress": "user2@example.com",
        "avatarUrls": {

        },
        "displayName": "user2",
        "active": true
      },
      {
        "self": "http://",
        "name": "user3",
        "emailAddress": "user3@example.com",
        "avatarUrls": {

        },
        "displayName": "user3",
        "active": true
      }
    ],
    "max-results": 50,
    "start-index": 0,
    "end-index": 3
  },
  "expand": "users"
}

Using just awk to interpret the sample json data:

$ awk -F: -v RS="," '$1~/"name"/ && f {gsub("[ \",]", "", $2); print $2} $1~/"name"/{f=1}' json
admin
edwin
niwde
other

The first match of name is skipped due to the flag f .

Explanation of awk code:

  • $1~/"name"/ && f {gsub("[ \\",]", "", $2); print $2}

    This consists of a condition and a group of statements. The condition requires that the first field match "name" and that the flag f is nonzero. If both those conditions are met, then spaces, quotes, and commas are removed from the same second field and the second field is printed.

    In awk , the default value for variables is zero (or blank). Consequently, nothing is printed until we assign f a non-zero value.

  • $1~/"name"/{f=1}

    If the first field matches on "name" , then the flag f is set to 1 . Thus, f is not set to 1 until after the first name field is seen. Thus, the first name field will not be printed but all after it will be.

你可以试试这个sed

sed -n '/"name": "/{s/ *"name": "\([^"]*\)",/\1/;p}' YourFile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM