gpt4 book ai didi

linux - Bash脚本grep文件中的字符串并输出到另一个文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:56:23 24 4
gpt4 key购买 nike

我写了一个 bash 脚本来 grep 一个字符串和后续的几行,然后输出到另一个文件。

这是我的 bash 脚本

#!/bin/bash

echo "$#"

if [ "$#" -ne 4 ]; then

echo "Usage : ./redirectTrace.sh searchText inputFile number_of_Lines_succeeding_the_searchText outputFile"

else

searchText=$0
inputFile=$1
lines=$2
outputFile=$3

echo "$0 , $2, $3, $4"

grep -i -A "$lines" "$searchText" $inputFile > $outputFile
fi

当我将其作为 ./redirectTrace.sh Drag::log/Test.log 10 Drag1.log 执行时,我得到

grep: log/Test.log: invalid context length argument

如果我不传递行数并使用固定值执行,我会收到另一个错误。

脚本:

grep -i -A 10 "$searchText" $inputFile > $outputFile

执行:./redirectTrace.sh Drag::log/Test.log Drag1.log`

我收到以下错误:

grep: Drag::: No such file or directory

log/Test.log 文件也变空了。

为什么?

最佳答案

主要是因为$0脚本 的名称,而不是脚本的第一个参数。第一个参数是$1,第四个参数是$4,以此类推

所以你的作业应该是:

searchText=$1
inputFile=$2
lines=$3
outputFile=$4

关于linux - Bash脚本grep文件中的字符串并输出到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39097597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com