【问题标题】:A Bash script that output lines in the files including a word一个 Bash 脚本,输出文件中的行,包括一个单词
【发布时间】:2021-05-13 14:48:21
【问题描述】:

如果我写一个sh file,脚本输入文件夹、文件类型(例如.txt)和一个单词的3个参数。我需要检查是否至少有 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=${1}
    type_file=${2}
    word=${3}
    # Show file contents with the word 
    echo "Lines that contains the ${word}:"
    # cat "${}

我不知道怎么用猫读取所有文件并检查然后打印。

【问题讨论】:

  • grep -w "$word" example.txt
  • @anubhava 这个代码是怎么写的?
  • 只需复制/粘贴给定命令到最后echo 行下方
  • 这看起来像是对your last question 的重述(现已关闭)。请注意,通常最好编辑一个封闭的问题来改进它,而不是问一个新的问题,这样读者就可以看到旧的上下文。不过,现在已经完成了。

标签: bash shell sh cat


【解决方案1】:

如果您只想打印匹配的行,请使用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=${1}
    type_file=${2}
    word=${3}
    # Show file contents with the word 
    echo "Lines that contains the ${word}:"
    cd "$folder_name"
    grep -F -w "$word" *."$type_file"
fi

【讨论】:

  • 在最后一行你的意思是 type_file 还是 file_type?
  • if test "$#" -lt 3; then echo "..." >&2; exit 1; fi
  • @WilliamPursell 我想过建议,但这更像是一个风格问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-10
  • 2017-12-07
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
相关资源
最近更新 更多