Extracting Lines in a File on a Shell Script

Asked 2 years ago, Updated 2 years ago, 84 views

There are two files: test1.txt (space separated), test2.txt, and
Could you tell me the code for the shell script to generate a file (test3.txt) that extracts the test1.txt line containing the test2.txt string?

■ test1.txt
AAA ab
BBB bc
CCC cd
DDDde
EEEef

■ test2.txt
AAA
CCC
EEE

■ test3.txt
AAA ab
CCC cd
EEEef

grep

2022-09-30 19:06

3 Answers

The grep -f ( --file=FILE) option would be good.

Read the -f FILE, --file=FILE pattern from the file as a line-by-line pattern. When using this option more than once or when combined with the -e(--regexp) option, search for all the patterns given.
Empty files do not match anything because they do not contain patterns.

https://linuxjm.osdn.jp/html/GNU_grep/man1/grep.1.html

Example Execution:

$grep-f test2.txt test1.txt>test3.txt
$ cat test3.txt
AAA ab
CCC cd
EEEef


2022-09-30 19:06

If your environment is Linux (GNU coreutils), you can use the join command.Equivalent to internal SQL merge.

$join test1.txt test2.txt
AAA ab
CCC cd
EEEef


2022-09-30 19:06

Using Redirect to Standard Input,

#!/bin/bash

while read line
do
        grep$line./test1.txt>>./test3.txt
done<./test2.txt

How about that?


2022-09-30 19:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.