Monday, May 6, 2024
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 428  / 2 Years ago, sat, november 5, 2022, 9:28:09

I have two text files. Text-file-1 contains strings (one string per line);



C 010
C 020
C 024
.
.
.


Text-file-2 contains data in following format;



C 005 Carbon
D Carbon 1
D Carbon 2
D Carbon 3
D Carbon 4
C 010 Hydrogen
D Hydrogen 1
D Hydrogen 2
C 017 Oxygen
D Oxygen 1
C 020 Nitrogen
D Nitrogen 1
D Nitrogen 2
D Nitrogen 3
C 024 Sulphur
D Sulphur 1
D Sulphur 2
.
.
.


Text-file-1 contains 30 lines but Text-file-2 contain huge data, and in the same format as I mentioned. I can grep the text in Text-file-2 found in Text-file-1 using following command;



awk 'NR==FNR { A[$2]=1; next }; A[$2]' Text-file-1 Text-file-2 > filename


Output for this script



C 010 Hydrogen
C 020 Nitrogen
C 024 Sulphur
.
.
.


My Desired output is;



C 010 Hydrogen
D Hydrogen 1
D Hydrogen 2
C 020 Nitrogen
D Nitrogen 1
D Nitrogen 2
D Nitrogen 3
C 024 Sulphur
D Sulphur 1
D Sulphur 2
.
.
.


Now, I need an extension of this command, which could print all lines (starting with "D"), including and after this line. All lines in Text-file-2 are starting with a letter (C or D). This letter is not useful for me, but I kept it. Kindly help.


More From » command-line

 Answers
6

Here is another possible solution, using sed



while read str; do sed -n "/^$str/,/^C/ {/^$str/p;/^D/p}" Text-file-2; done < Text-file-1


Be aware that substituting shell variables into sed expressions should be used with care. It's OK in this case because Text-file-1 contains simple alphanumeric strings, but it will fail if the shell variable contains any 'special' characters that need to be escaped within the sed expression.


[#29392] Saturday, November 5, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gerrin

Total Points: 347
Total Questions: 109
Total Answers: 121

Location: Tanzania
Member since Fri, Oct 29, 2021
3 Years ago
gerrin questions
Sun, Sep 25, 22, 12:20, 2 Years ago
Sat, Sep 11, 21, 20:11, 3 Years ago
Tue, Jan 11, 22, 22:26, 2 Years ago
Thu, Oct 28, 21, 14:34, 3 Years ago
Sat, Mar 12, 22, 10:03, 2 Years ago
;