【问题标题】:Linux - Bash Redirect a String to a fileLinux - Bash 将字符串重定向到文件
【发布时间】:2014-10-17 16:52:13
【问题描述】:

我写了一个简单的脚本,它读取文件内容并在这个文件中增加一个数字,然后我使用 awk 保存更改,当我尝试使用 '>' 重定向新字符串时,整个字符串是重定向在一行中,而不是像原来的那样是 4 行。

#!/bin/bash -x

# This script is for Incrementing build numbers

path=/home/RND/abrodov
file=tst.txt
tst=`cat $path/$file`
printf "this is the content of the file before incrementing: \n $tst"
newexpr=`awk '/^Build Number/{$4=$4+1;}1' /home/RND/abrodov/tst.txt`
printf "\n the new content \n $newexpr"
echo $newexpr > $path/$file

这是运行脚本之前的原始文件:

Major Release Number = 4
Minor Release Number = 1
Service Pack Release Number = 2
Build Number = 22

这是我使用脚本后的内容:

Major Release Number = 4 Minor Release Number = 1 Service Pack Release Number = 2 Build Number = 23

我试图弄清楚如何以 4 行的原始格式重定向文本。

【问题讨论】:

    标签: linux bash shell awk sed


    【解决方案1】:

    您需要将变量用双引号括起来:

    echo "$newexpr" > "$path/$file"
    

    在这种情况下,$path/$file 周围的引号实际上并不是必需的,但它们没有害处。

    更一般地,您还应该使用$( ) 而不是反引号:

    newexpr=$(awk '/^Build Number/{$4=$4+1;}1' "$path/$file")
    

    如果要达到“就地”改变文件的效果,不需要使用变量。您可以使用这样的临时文件:

    awk '/^Build Number/{$4=$4+1;}1' "$path/$file" > /tmp/file && mv /tmp/file "$path/$file"
    

    使用引号的重要性

    双引号保留数据的原始格式。请看这个简单的例子,它使用set -x 来激活调试模式。 shell 正在执行的命令显示在以+ 开头的行上。 其实我看到你已经在使用#!/bin/bash -x了。 set -x 做同样的事情。:

    $ s="1
    > 2"
    $ set -x
    $ echo $s
    + echo 1 2
    1 2
    $ echo "$s"
    + echo '1
    2'
    1
    2
    

    原始字符串包含换行符,但当您将echo 不带引号时,它会被解释为echo 的两个参数,而不是一个包含换行符的参数。这称为字段拆分。您可以阅读此this wiki article,详细了解使用双引号的重要性。

    【讨论】:

      猜你喜欢
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2021-11-04
      • 2011-07-22
      相关资源
      最近更新 更多