1

This question already has an answer here:

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.

marked as duplicate by don_crissti, Eric Renouf, Anthony Geoghegan, Kusalananda shell-script Aug 17 '18 at 17:55

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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

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
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|
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| . . .
$

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