Bash菜单一个答案就是在多个文件中更改ip

时间:2013-09-16 17:59:42

标签: bash

我想在两个文件中修改IP:

File1 的内容包含以下内容:

AS400=127.0.0.1

File2 的内容包含以下内容:

AS400=127.0.0.1

下面的bash脚本会询问我AS400的IP地址,目前只修改一个文件:

    #!/bin/bash
    # Modify props file - file1.props
echo " Please answer the following question"    
gawk -F"=" 'BEGIN{
    printf "Enter AS400 IP: "
    getline as400 <"-"
    file="/usr/local/src/file1.props"
    }
    /as400/ {$0="as400="as400}
    {
    print $0 > "temp2"
    }
    END{
    cmd="mv temp2 "file
    system(cmd)
    }
    ' /usr/local/src/file1.props

如何告诉它更新我输入 file2 的完全相同的IP地址?

奖金问题...... 任何人都可以看看这个脚本并告诉我为什么编辑的文件最终会在每一行的末尾加上^ M?

3 个答案:

答案 0 :(得分:2)

使用临时文件并使用mv调用system(),而不是包装awk,您可以只使用bash作为整体:

#!/bin/bash

[[ BASH_VERSINFO -ge 4 ]] || {
    echo "You need bash version 4.0 to run this script."
    exit 1
}

read -p "Enter AS400 IP: " IP

FILES=("/usr/local/src/file1.props" "/usr/local/src/file2.props")

for F in "${FILES[@]}"; do
    if [[ -f $F ]]; then
        readarray -t LINES < "$F"
        for I in "${!LINES[@]}"; do
            [[ ${LINES[I]} == 'as400='* ]] && LINES[I]="as400=${IP}"
        done
        printf "%s\n" "${LINES[@]}" > "$F"
    else
        echo "File does not exist: $F"
    fi
done

将其保存到脚本并运行bash script.sh

您也可以修改它以接受自定义文件列表。替换此行

FILES=("/usr/local/src/file1.props" "/usr/local/src/file2.props")

使用

FILES=("$@")

然后使用like:

运行脚本
bash script.sh "/usr/local/src/file1.props" "/usr/local/src/file2.props"

答案 1 :(得分:0)

实际上,如果您取消了交互式提示,并且使用了命令行参数,那么脚本可以变得更简单,更优雅和可用。

#!/bin/sh
case $# in
    1) ;;
    *) echo Usage: $0 '<ip>' >&2; exit 1;;
esac

for f in file1.props file2.props; do
    sed -i 's/.*as400.*'/"as400=$1"/ /usr/local/src/"$f"
done

如果您的sed不支持-i选项,请回退到原始脚本中的临时文件回转。

答案 2 :(得分:0)

#!/bin/bash
read -p "Enter AS400 IP: " ip
sed -i '' "s/\(^as400=\)\(.*\)/\1$ip/" file1 file2

至于你的奖金,请看:'^M' character at end of lines