一个 Bash 脚本,输出文件中的行,包括一个单词
A Bash script that output lines in the files including a word
如果我写 sh file
,脚本输入文件夹的 3 个参数、文件类型(例如 .txt
)和一个单词。我需要检查是否至少有 3 个参数,如果没有打印消息,然后读取文件夹名称中的所有文件并打印包含类型文件单词的所有行。
例如我有 folder_name-->myScript.sh example.txt
并且在 example.txt
中我们有文本:
hello word
hello everybody
good bye
当我 运行 "./example.sh folder_name hello txt"
将输出:
hello world
hello everybody
我试着写这个:
#!/bin/bash
# Checking number of arguments.
if test "$#" -lt 3
then
echo "no enough arguments"
else
folder_name=
type_file=
word=
# Show file contents with the word
echo "Lines that contains the ${word}:"
# cat "${}
我不会用cat读取所有文件并检查然后打印。
如果只想打印匹配行,请使用 grep
,而不是 cat
。
通配符 *."$type_file"
将匹配具有给定后缀的所有文件。
所以命令应该是:
cd "$folder_name"
grep -F -w "$word" *."$type_file"
-F
选项匹配$word
作为固定字符串,而不是正则表达式。 -w
使其匹配整个单词,而不是单词的一部分。
如果您不想在所有匹配行之前看到文件名,请添加 -h
选项。
#!/bin/bash
# Checking number of arguments.
if test "$#" -lt 3
then
echo "no enough arguments"
else
folder_name=
type_file=
word=
# Show file contents with the word
echo "Lines that contains the ${word}:"
cd "$folder_name"
grep -F -w "$word" *."$type_file"
fi
如果我写 sh file
,脚本输入文件夹的 3 个参数、文件类型(例如 .txt
)和一个单词。我需要检查是否至少有 3 个参数,如果没有打印消息,然后读取文件夹名称中的所有文件并打印包含类型文件单词的所有行。
例如我有 folder_name-->myScript.sh example.txt
并且在 example.txt
中我们有文本:
hello word
hello everybody
good bye
当我 运行 "./example.sh folder_name hello txt"
将输出:
hello world
hello everybody
我试着写这个:
#!/bin/bash
# Checking number of arguments.
if test "$#" -lt 3
then
echo "no enough arguments"
else
folder_name=
type_file=
word=
# Show file contents with the word
echo "Lines that contains the ${word}:"
# cat "${}
我不会用cat读取所有文件并检查然后打印。
如果只想打印匹配行,请使用 grep
,而不是 cat
。
通配符 *."$type_file"
将匹配具有给定后缀的所有文件。
所以命令应该是:
cd "$folder_name"
grep -F -w "$word" *."$type_file"
-F
选项匹配$word
作为固定字符串,而不是正则表达式。 -w
使其匹配整个单词,而不是单词的一部分。
如果您不想在所有匹配行之前看到文件名,请添加 -h
选项。
#!/bin/bash
# Checking number of arguments.
if test "$#" -lt 3
then
echo "no enough arguments"
else
folder_name=
type_file=
word=
# Show file contents with the word
echo "Lines that contains the ${word}:"
cd "$folder_name"
grep -F -w "$word" *."$type_file"
fi