How can I print 2 lines if the second line contains the same match as the first line?

Ryan Ward

Let's say I have a file with several million lines, organized like this:

@1:N:0:ABC
XYZ

@1:N:0:ABC
ABC

I am trying to write a one-line grep/sed/awk matching function that returns both lines if the NCCGGAGA line from the first line is found in the second line.

When I try to use grep -A1 -P and pipe the matches with a match like '(?<=:)[A-Z]{3}', I get stuck. I think my creativity is failing me here.

Sundeep

With awk

$ awk -F: 'NF==1 && $0 ~ s{print p ORS $0} {s=$NF; p=$0}' ip.txt
@1:N:0:ABC
ABC
  • -F: use : as delimiter, makes it easy to get last column
  • s=$NF; p=$0 save last column value and entire line for printing later
  • NF==1 if line doesn't contain :
  • $0 ~ s if line contains the last column data saved previously
    • if search data can contain regex meta characters, use index($0,s) instead to search literally
  • note that this code assumes input file having line containing : followed by line which doesn't have :


With GNU sed (might work with other versions too, syntax might differ though)

$ sed -nE '/:/{N; /.*:(.*)\n.*\1/p}' ip.txt
@1:N:0:ABC
ABC
  • /:/ if line contains :
  • N add next line to pattern space
  • /.*:(.*)\n.*\1/ capture string after last : and check if it is present in next line

again, this assumes input like shown in question.. this won't work for cases like

@1:N:0:ABC
@1:N:0:XYZ
XYZ

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

How can I make a substitution on the line of first occurrence of a match only?

Gratient Module how can i print text in the same line

compare first word for each line in csv file and print the line which match and on failure also print lines not matching first word

How to print out to lines together while using for loop? I couldn't figure out how to print everything in the same line - java

how can I sort a field form an Endnote Export File format where the Line contains GRAZ in the address as first line?

How can I print text in two different colours (console) on the same line?

How do I put a print statement on the same line as a return statement?

How can I insert a new line into a text file into every other 2 lines?

PHP sscanf doesn't print first line in file but the following lines

phpcs: How can I modify PSR2 to check that the brace is on the same line as the method?

How can I skip the first and the last line of a file in PHP

How to match the string after first character in a line

C# - How can I initilalize List<string[]> in the same line

How can I get the information table and image aligned on the same line

How can I align a Material icon & header text on the same line?

How can I change this code so it prints on the same line?

Storing lines into array and print line by line

Can I perform a 'non-global' grep and capture only the first match found for each line of input?

How do I make sure the line that appears under the first column is moved to the second column on top

awk: first, split a line into separate lines; second, use those new lines as a new input

How to stop match at first occurence of a match on each line?

How to print a line only if it contains a specific string using groovy?

How do I print the first line of a file after sorting without the last value in powershell?

How to print line X lines prior to correct if statement

Command line piping to match first line of output

How to reduce the indentation between first and second line inside circle?

How can I read in a TXT file in Access that is over 255 char/line and contains control char?

Cannot print output on the same line

How can I sort list lines by time if the times are in different locations in the line?

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo