-6

Given a space delimited text file, look for pattern in the first column. If found, keep the first occurence and delete the other lines:

Input (pattern = 1234):

1234    1111    2222
5678    3333    4444
1234    5678    9012
5678    1234    5678
1234    9786    5432

Expected Output:

1234    1111    2222
5678    3333    4444
5678    1234    5678
  • 5
    This should be very simple... Have you tried anything (search google) ? – don_crissti Oct 30 '16 at 18:27
  • For the life of me, I cannot match your desired output to your question! – maulinglawns Oct 30 '16 at 18:46
  • 3
    Please make a good faith attempt to solve the problem yourself first. – phk Oct 30 '16 at 18:50
2

So you want to print all lines where the first field is not the specified value, and print the first line where it does match.

awk -vF="$1" '{ if ($1 != F) { print; } else {if (!seen) { print ; seen=1}}}'

Uses the fact that awk variables (seen in this case) have a value of 0 initially.

  • More compactly (making use of short circuit evaluation), awk -v F='1234' '$1 != F || !seen++' input – steeldriver Nov 1 '16 at 2:53
  • I agree, that is pretty much what I would write for my own use (I wouldn't bother with setting the F variable, just get the quoting correct). I was going for clarity. I almost put in $0 on the print statements to make it clearer. – icarus Nov 1 '16 at 3:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.