1

I have this following structure in file.txt

NTL|OPC|RN1|CNL|NUE|NUF|TPB|EIP
11212455464       |16384|55320|     |2799819E405       |                  |2|                                                  
32545687784       |16384|55320|     |1194155B581       |                  |2|                                                  
54565487788       |16384|55321|     |8599132D051       |                  |2|                                                  
23154688789       |4013|55115|11529|163624D585        |16D7620595        |1| 
...

and I want this result (the title plus the queried value)

NTL|OPC|RN1|CNL|NUE|NUF|TPB|EIP
23154688789       |4013|55115|11529|163624D585        |16D7620595        |1| 

I tried something like this

head -1 file.txt | grep 23154688789

but it does not work.

Chris Davies
  • 116,213
  • 16
  • 160
  • 287

4 Answers4

2

If you can use sed instead, you can have it print line 1 and any line that matches like

sed -n -e '1p;/23154688789/p' file.txt

-n will tell it not to print output unless directed to, 1p says print line 1 and /23154688789/p prints any line that matches that pattern

Eric Renouf
  • 18,431
1

In your code replace '|' with ';' head gives you first line and piping it into grep makes grep search only in first line. You need something like this:

head -n 1 file.txt ; grep 23154688789 file.txt
Alexander
  • 1,416
1

The awk command will allow this. Here we output the line if the Record Number (NR) is 1 or we get a match on the first field:

awk -v id=23154688789 'NR==1 || $1==id'

Result

NTL|OPC|RN1|CNL|NUE|NUF|TPB|EIP
23154688789       |4013|55115|11529|163624D585        |16D7620595        |1|
Chris Davies
  • 116,213
  • 16
  • 160
  • 287
0

Assuming the only line starting with "NTL" will be the header line, a single grep can be used to achieve this.

$ grep -E '^NTL|23154688789' file.txt
NTL|OPC|RN1|CNL|NUE|NUF|TPB|EIP
23154688789 |4013|55115|11529|163624D585 |16D7620595 |1| . . .
$
steve
  • 21,892