gpt4 book ai didi

Linux - Bash 将字符串重定向到文件

转载 作者:IT王子 更新时间:2023-10-29 00:17:17 25 4
gpt4 key购买 nike

我写了一个简单的脚本,它正在读取文件内容并在这个文件中递增一个数字,然后我使用 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 行的原始格式重定向文本。

最佳答案

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

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 激活 Debug模式。 shell 正在执行的命令显示在以 + 开头的行中。 实际上我看到您已经在使用 #!/bin/bash -xset -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 了解更多关于使用双引号的重要性。 .

关于Linux - Bash 将字符串重定向到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25470652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com