【问题标题】:How to write in the middle of a file (Bourne Shell script)如何在文件中间写入(Bourne Shell 脚本)
【发布时间】:2013-01-08 13:09:24
【问题描述】:
我有某种数据库文件:
key1 val1
key2 val2
key3 val3
...
我想写“hello”而不是 val1
我想做什么:
while read line
do
var= cut -d ' ' -f 1
if [ $var == "key1" ]
then
????
fi
done < myfile
有没有办法使用 FD 重定向? (或者如果有某种偏移,则回声?...)
【问题讨论】:
标签:
linux
shell
sed
replace
【解决方案1】:
对于简单的替换使用sed:
sed 's/val1/hello/' file
如果val1 在一行中出现多次,这将用hello 替换每行上val1 的第一个实例,然后添加全局标志g,例如:
sed 's/val1/hello/g' file
sed 的默认行为是打印到stdout,以便将更改保存到新文件使用重定向:
sed 's/val1/hello/g' file > newfile
或使用sed 的-i 选项将更改保存在原始文件中:
sed -i 's/val1/hello/g' file
【解决方案2】:
如果你真的需要 shell 解决方案:
while read key val ; do
if [ "$key" == key1 ] ; then
val=hello
fi
echo "$key $val"
done < myfile
【解决方案3】:
您要查找的内容称为“关联数组”,在 Perl 中也称为“哈希”,或“键值存储”或“字典查找”。 Bourne shell 不直接支持它们。 Awk、Perl 和 Bash 都有关联数组。有一些方法可以在 bourne shell 中将关联数组组合在一起,但它们很丑陋。您最好的选择是 a) 选择一种更适合手头任务的语言或 b) 如果您必须使用 bourne shell,请使用更强大的语言围绕关联数组编写一个包装函数(这本质上是 sudo_O 使用 sed 所做的)。
#! /bin/sh
lookup() {
perl -e '%hash = ( "key1" => "hello", "key2" => "val2", "key3" => "val3" );
print $hash{ $ARGV[0] }
' $1
}
x=$(lookup "key1")
echo $x
这比纯 bourne shell 的便携性差,但如果你有 perl 可用,这是一条更容易的路线。
如果您没有在包装器中使用 perl,那么最好的选择是 awk——它基本上可以在任何具有 sed 的机器上使用,并且它对关联数组具有一流的支持。