Shell searches for keywords in batches and saves the results to a file (array, loop)

 

#!/bin/bash

keywords =( " No need "  " No thank you "  " xxx "  " xxx " )

for var in ${keywords[@]}
do
        echo $var
        cat ../corpus.txt | grep $var | wc -l        
        cat ../corpus.txt | grep $var > search_res/$var.txt
done

 

1. Shell Arrays
Arrays can hold multiple values. Bash Shell only supports one-dimensional arrays (multi-dimensional arrays are not supported), and the array size does not need to be defined during initialization (similar to PHP).

Similar to most programming languages, the subscripts of array elements start at 0.

Shell arrays are represented by brackets, and elements are separated by "space" symbols . The syntax is as follows:

array_name=(value1 ... valuen)

We can also use subscripts to define arrays:

array_name[0]=value0
array_name[1]=value1
array_name[2]=value2

The general format for  reading the value of an array element is: ${array_name[index]} 

Get all elements in an array
Use @ or * to get all elements in an array, for example:

echo  " The elements of the array are: ${my_array[*]} " 
echo  " The elements of the array are: ${my_array[@]} "

The method to get the length of an array is the same as the method to get the length of a string, for example:

echo  "The number of elements in the array is: ${#my_array[*]} " 
echo  "The number of elements in the array is: ${#my_array[@]} "

 

2. for loop in shell flow control

Similar to other programming languages, Shell supports for loops.

The general format of a for loop is:

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

Written in one line:

for var in item1 item2 ... itemN; do command1; command2… done;

When the variable value is in the list, the for loop executes all commands once, using the variable name to get the current value in the list. Command can be any valid shell command and statement. The in list can contain substitutions, strings, and filenames.

The in list is optional, and without it, the for loop uses the command-line positional arguments.

For example, to sequentially output the numbers in the current list:

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

Output result:

The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5

Sequentially output characters in a string:

for str in 'This is a string'
do
    echo $str
done

Output result:

This is a string

 

refer to:

Shell Arrays | Beginner Tutorial

Shell Process Control | Rookie Tutorial

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324830635&siteId=291194637