1

How would I write a bash script that parses a text file, finding any lines that contain the word command: and then saves the entirety of each line on which it was found on to a text file?

methuselah
  • 12,766
  • 47
  • 165
  • 315

2 Answers2

3

The command would be

grep command: your_filename >> save_filename

Which is

#!/bin/bash
grep command: $1 >> $2

Executed by

scriptname your_filename save_filename

Thanks David

Note that I'm using an appender >>, instead of a create >. The latter ensures a file with only your last run in it, whereas the appender will add new lines to the file if it already exists.

user1442498
  • 305
  • 2
  • 10
  • Or run `grep` in a subshell and redirect (truncate/write) once, e.g. (`grep command: your_filename) > save_filename`. Either way is fine, but you may want an `:>your_filename` before the `grep` call to insure `your_filename` is empty to begin with using the `>>` append redirection. – David C. Rankin Oct 10 '17 at 00:03
0

If you are looking for a pure bash solution of this grep-like behaviour:

#!/bin/bash
# Usage: ./mygrep ERE_PATTERN FILENAME
while IFS= read -r line || [[ $line ]]; do
    [[ $line =~ $1 ]] && echo "$line"
done <"$2"

(We iterate over lines of the file given in the second positional parameter, $2, in a pretty standard way, checking for a match with a pattern given as the first parameter inside a conditional expression with the =~ operator, printing all lines that match.)

Invoke it like:

./mygrep command: file

Although much slower than grep, one nice thing about this script is that it supports POSIX ERE (extended regular expressions) by default (you don't need to specify -E like you do in grep), e.g.:

./mygrep 'com.*:' file
./mygrep '^[[:digit:]]{3}' file
# etc
randomir
  • 17,989
  • 1
  • 40
  • 55