-1

Lets say I have this input

11
12
31
40
42
90

I need to get all number lines from the file and add the | character after each that can be used as a pattern list to run with grep -f.

I was thinking of using xargs but I have no idea how to use | as a separator or put the args in the middle of a string

grep -P "(11|12|31|40|42|90)\|" o.txt
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Eric Stotch
  • 141
  • 4
  • 19
  • 4
    You can just use that file with `-f`? – daniu Nov 24 '21 at 07:02
  • @daniu almost. I need to add `\|` to the end of each line and maybe something at the start. I completely forgot grep can use `-f` – Eric Stotch Nov 24 '21 at 07:19
  • No unless I misunderstand it. I need any numbers in the file and the character `|` after it. I do not want the first number `|` second number `|` etc. It also looks like I might want a suffix and I'm a little unsure how to add it without a space but maybe I'll use a python script since I know how to debug it – Eric Stotch Nov 24 '21 at 07:26
  • 1
    Give an example input which shows what is the expected outcome. I honestly don't see what you want to achieve. Also explain in what respect the `grep` statement you have suggested, does not work correctly. – user1934428 Nov 24 '21 at 07:54
  • BTW, in your pattern, I don't see why you need `-P`. Wouldn't `-E` be sufficient? – user1934428 Nov 24 '21 at 07:55

1 Answers1

1

You can use

grep -E -f <(sed -E '/^[0-9]+$/!d;s/.*/&\\|/' numbers.txt) file.txt

First, get all lines that only contain digit from the numbers.txt, append to each found line a \|, and then use this as a pattern file with -f option to grep. The file.txt is a file where you are looking for matches.

See an online demo:

#!/bin/bash
text='Some 11 number and 11| that we need
Redundant line'
s="11
12
31
40
42
90"
grep -E -f <(sed -E '/^[0-9]+$/!d;s/.*/&\\|/' <<< "$s") <<< "$text"
# => Some 11 number and 11| that we need
grep -oE -f <(sed -E '/^[0-9]+$/!d;s/.*/&\\|/' <<< "$s") <<< "$text"
# => 11|
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563