用bash中的变量循环多行文本

时间:2014-03-12 00:42:27

标签: bash

我试图为某些单词grep所有/ home目录。如果出现这些单词,它会写一个/ var / logfile,然后从那里我想要逐行读取,然后用信息回显每一行。这是我到目前为止所做的。

grep -r -i "word\|word\|word\|word\|word" /home >>/var/testlog

UNAME=`grep -r -i "word\|word\|word\|word\|word" /var/testlog | cut -f 3 -d "/"`
BLINE=`grep -r -i "word\|word\|word\|word\|word" /var/testlog | cut -f 2 -d ":"`
FILEP=`grep -r -i "word\|word\|word\|word\|word" /var/testlog | cut -f 1 -d ":"`

while [ "$UNAME" == "true" ] && [ "$BLINE" == "true" ] && [ "$FILEP" == "true" ];
do

echo "User is: $UNAME, The line flag with the word is: $BLINE, and the file path for the text is: $FILEP."

done

1 个答案:

答案 0 :(得分:0)

一个解决方案是:

grep -r -i "word\|word\|word\|word\|word" /home >>/var/testlog
while IFS= read -r line
do
    [[ $line =~ (/home)/([^/]+)/([^:]*):(.*) ]] || echo Failed on line=$line
    echo "User is: ${BASH_REMATCH[2]}, The line flag with the word is: ${BASH_REMATCH[4]}, and the file path for the text is: ${BASH_REMATCH[1]/${BASH_REMATCH[2]}}/${BASH_REMATCH[3]}."
done <testlog

如果允许使用sed,则不需要while循环:

grep -r -i "word\|word\|word\|word\|word" /home >>/var/testlog
sed -r 's|(/home/(\w+)/[^:]*):(.*)|User is: \2, The line flag with the word is: \3, and the file path for the text is: \1.|' testlog
相关问题