繁体   English   中英

使用文本文件作为参数将Shell stderr重定向到另一个文件

[英]Shell stderr redirection to another file using a text file as a argument

我编写了一个bash脚本,它将读取参数中已经提供的文本文件,并将处理文本并将错误重定向到错误文件,并将其他输出重定向到list.txt文件。

#!/bin/bash
filename="$1"
while read line; do
        a=$(echo $line | awk "{print NF}")
                if [ "$a" = "3" ]
                then
                        first=$(echo $line | awk -F' ' '{print $1}')
                        last=$(echo $line | awk -F' ' '{print $2}')
                        email=$(echo $line | awk -F' ' '{print $3}')
                        if [[ $first =~ ^[a-zA-Z]+$ && $last =~ ^[a-zA-Z]+$ ]]
                        then
                                if [[ $email =~ '<([\w\.\-_]+)?\w+@[\w-_]+(\.\w+){1,}>' ]]
                                then
                                        echo "$first $last $email" | cat >>list.txt
                                elif [[ $email =~ '([\w\.\-_]+)?\w+@[\w-_]+(\.\w+){1,}' ]]
                                then
                                        echo "$first $last <$email>" | cat >>list.txt
                                else
                                        echo "$first $last $email" | cat >&2
                                fi
                        else
                                echo "$first $last $email" | cat >&2
                        fi
                else
                        echo "$line" | cat >&2
                fi
        done < $filename

我将这段代码作为$。/ script.sh argumentsfile.txt 2> error.txt运行

我的论点文件包含以下信息

Joe cable cable@ablecorp.com
Bob Brown <bob_baker@bakerandsons.com>
Jim Hass  hass@bigcorp.com
mike_lupo@mou.east.com
Edison jones jones@inl.net.gov
pirate.coe.su.com pirate people

文件的理想形式应为(格式有意不良)

lastname firstname <email> 

在错误文件中我得到的是

 Joe cable cable@ablecorp.com
Bob Brown <bob_baker@bakerandsons.com>
Jim Hass  hass@bigcorp.com
mike_lupo@mou.east.com
Edison jones jones@inl.net.gov
pirate.coe.su.com pirate people

您可以使用awk完全完成此操作:

#!/bin/bash

gawk '{

name_re = "^[[:alpha:]]+$"
mail_re = "<?[[:alnum:]_.%+-]+@[[:alnum:]_.-]+\\.[[:alpha:]]{2,6}>?"

# check for 3 fields with suitable regexp matching for all
if (NF == 3 && $1 ~ name_re && $2 ~ name_re && $3 ~ mail_re) {
    # put brackets around the address if needed
    email = $3 ~ /^<.*?>$/ ? $3 : "<" $3 ">"
    # output to the good list
    print $1 " " $2 " " email > "list.txt"
    # move to the next one
    next
}

# output to the bad list
print > "error.txt"

}' "$1"

使用awk BSD和Gnu版本进行了测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM