我想修改两个文件中的 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?
与其包装 awk,使用临时文件并使用 system()
调用mv
,不如整体使用 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 "%sn" "${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=("$@")
然后像这样运行脚本:
bash script.sh "/usr/local/src/file1.props" "/usr/local/src/file2.props"
实际上,如果您取消交互式提示,而是使用命令行参数,则可以使脚本更简单,更优雅和可用。
#!/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
选项,请回退到原始脚本中的临时文件回转。
#!/bin/bash
read -p "Enter AS400 IP: " ip
sed -i '' "s/(^as400=)(.*)/1$ip/" file1 file2
至于你的奖金,看看这个:行尾的"^M"字符