繁体   English   中英

如何在文件中间写入(Bourne Shell脚本)

[英]How to write in the middle of a file (Bourne Shell script)

我有某种数据库文件:

key1 val1
key2 val2
key3 val3
...

我想写“你好”而不是val1

我试图做的:

while read line
do
    var= cut -d ' ' -f 1
    if [ $var == "key1" ]
    then
        ????
    fi
done < myfile

有没有办法使用FD重定向? (如果存在某种偏移,还是回声?...)

对于简单的替换,请使用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

如果你真的需要一个shell解决方案:

while read key val ; do
    if [ "$key" == key1 ] ; then
        val=hello
    fi
    echo "$key $val"
done < myfile

您正在寻找的是一个'关联数组',也称为Perl中的'hash',或'Key-value store'或'dictionary-lookup'。 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的机器上使用,并且它具有对关联数组的一流支持。

暂无
暂无

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

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