Search code examples
linuxshellread-text

Reading text in Linux shell and writing some specific rows to a new file


I have a file with information with this format (input.txt):

045002   1987244NDBC North L. Mich. 453086401 176  5
045002   1999140NDBC North L. Mich. 453186421 176  5
045002   2006117NDBC North L. Mich. 453386421 176  5
045002   2007127NDBC North L. Mich. 453386431 176  5
045002   2009138NDBC North L. Mich. 453486411 176  5
045007   1987244NDBC South L. Mich. 427087101 176  5
045007   1991091NDBC South L. Mich. 428087101 176  5
045007   1991154NDBC South L. Mich. 427087101 176  5
045007   1995237NDBC South L. Mich. 427087001 176  5
045007   1999140NDBC South L. Mich. 426787021 176  5
045007   2006117NDBC South L. Mich. 426887031 176  5
045007   2009127NDBC South L. Mich. 426787031 176  5
045007   2010133NDBC South L. Mich. 427086971 176  5
045007   2011145NDBC South L. Mich. 426887031 176  5
045007   2012100NDBC South L. Mich. 426787031 176  5
045013   2012212UWM Atwater Park WI 431087851 176  2
045014   2012224UWM Green Bay WI    448087761 176  2
045018   2011222CPD MontroseBeach IL419787641 176  3 00011110
045020   2007230UGLOS GrandTrav Bay 447985601 176  2

I need to read this file in a Linux shell and create an output file that contains some specific rows of the input file based on the number in the first column, e.g., 045002, 045013, 045018. The output file (output.txt) should look like this:

045002   1987244NDBC North L. Mich. 453086401 176  5
045002   1999140NDBC North L. Mich. 453186421 176  5
045002   2006117NDBC North L. Mich. 453386421 176  5
045002   2007127NDBC North L. Mich. 453386431 176  5
045002   2009138NDBC North L. Mich. 453486411 176  5
045013   2012212UWM Atwater Park WI 431087851 176  2
045018   2011222CPD MontroseBeach IL419787641 176  3 00011110

Solution

  • If numbers.txt is a list of numbers:

    sed 's/.*/^&/' numbers.txt | grep -f - input.txt > output.txt
    

    Or the numbers can be on the command line:

    printf "^%s\n" 045002 045013 045018 | grep -f - input.txt > output.txt