Zombo
Zombo

Reputation: 1

awk return preferred matches

Given this file

$ cat foo.txt
0 blah
0 blah
1 blah
2 blah
0 blah

I have this command

$ awk '/[12]/' foo.txt
1 blah
2 blah

However I would only like to search for 1 lines if no 2 lines are found. Desired output for this file would be

2 blah

Upvotes: 1

Views: 82

Answers (4)

anubhava
anubhava

Reputation: 785058

awk '
/^1/ {
  a[i++] = $0
}
/^2/ {
  b[j++] = $0
}
END {
  if (length(b)) for (p in b) print b[p]
  else for (p in a) print a[p]
}
' foo.txt

Upvotes: 2

Zombo
Zombo

Reputation: 1

I ended up using this command, it works for me because I only need the first match of 2 or 1

awk '
/^[12]/ {
  c=$1
  if (c==1 && m) next
  m=$0
  if (c==2 && m) exit
}
END {
  print m
}
' FPAT=. foo.txt

Upvotes: 0

Mark Setchell
Mark Setchell

Reputation: 207425

You can do this with grep easily enough too:

twos=$(grep 2 yourfile)
if [ $? -eq 1 ]; then grep 1 yourfile; else echo $twos; fi

Upvotes: 0

janos
janos

Reputation: 124646

/^2/ {
    found = 1
    print
}
! found && /^1/ {
    matches[++i] = $0
}
END {
    if (! found) {
        for (i in matches) print matches[i]
    }
}

Upvotes: 3

Related Questions