grep包含特定字符串的行(一行可以写在最多3行)

时间:2015-12-01 13:32:06

标签: linux shell

我需要在我的项目中完成所有日志。 我使用此命令执行此操作:

grep -rnw $1 -e "Logger.[view]*;$" >> log.txt

此行返回包含Logger的所有行。[其中一个caracters] 包含在项目目录" $1"除了有一些线写在2或3行(IDE格式)。在这种情况下,我只获得第一行。 我该怎么做才能获得该日志的完整文本,知道日志行总是以" );" 这种线的例子:

Logger.v(xxxxxxxxxxxxx
xxxxxxxxxxxxxxxx);

这是我的剧本:

#!/bin/bash    
echo "Hello Logger!
# get project path 
echo "project directory is $1"
# get all project logs and store them into temporary file tmp.txt for processing
grep -rnw $1 -e "Logger.[view]" >> tmp.txt
echo "tmp.txt created successfully"
# remove package name from previous result and store result into log.txt
sed -r 's/.{52}//' tmp.txt >> log.txt
echo "log.txt created successfully"

grep命令返回 file_path / file_name line_number 。 我发现此命令只返回,即使它是用2行或3行写入但没有 file_path file_name line_number

sed -n '/Logger.[viewd]/{:start /;/!{N;b start};/Logger.[viewd]/p}' Main.java

有没有办法将这两个结果合并在一起。 例如:

/home/xxx/xxx/xxx/Main.java:97:Logger.i(xxxxxxxxxxxxx);    
/home/xxx/xxx/xxx/Main.java:106:Logger.d(yyyyyyyyyyyy
    yyyyyyyyyyyyyyyyyyyy);

2 个答案:

答案 0 :(得分:0)

我认为这是一个突破线问题。尝试通过以下行替换grep -rnw $1 -e "Logger.[view]" >> tmp.txt

for i in `ls $1`;
do
 cat $1/$i | tr '\n' ' ' | grep -rnw -e "Logger.[view]" >> tmp.txt
done

在这里,tr '\n' ' '用简单的空格替换断行。

答案 1 :(得分:0)

我找到了解决问题的方法,这是我的代码:

# get all project logs and store them into log.txt for processing
for i in $(find -name "*.java")
do
echo  >> log.txt
echo "**************** file $i ********************************" >> log.txt
echo  >> log.txt
    grep -rnw Logger.[viewd] $i | while read -r line ; do

    # remove breaklines from first line to avoid having bad results
    line="$(echo $line | sed $'s/\r//')"

    # if first line ends with ");" print it to log file
    if [[ ${line: -2} == ");" ]]; then
        echo $line >> log.txt

    # else get next line also
    else
        # get second line number
        line_number="$(echo "$line" | cut -d : -f1)"
        next_line_number=$((line_number+1))
        # get second line
        next_line=$(sed "${next_line_number}q;d" $i | sed -e 's/^[ \t]*//')
        # concatenate first line & second line
        line="$line $next_line"
        # print resulting line to log file
        echo $line >> log.txt
    fi
done