gpt4 book ai didi

bash - Shell脚本逐行读取一个文件

转载 作者:行者123 更新时间:2023-11-29 09:09:12 25 4
gpt4 key购买 nike

我是 shell 脚本的新手。我需要读取一个适用于所有 shell 的文件,该文件中定义了变量。像这样的东西:

variable1=test1
variable2=test2
....

我必须逐行读取此文件并准备由空格分隔的新字符串,例如:

variable=variable1=test1 variable2=test2 ....

我尝试了以下代码:

while read LINE
do
$VAR="$VAR $LINE"
done < test.dat

但它抛给我这个错误:

command not found Test.sh: line 3: = variable1=test1

最佳答案

您的脚本的问题是 var 初始化之前的前导 $,请尝试:

#/bin/bash

while read line; do
var="$var $line"
done < file

echo "$var"

但是,您可以使用 tr 命令通过将换行符替换为空格来执行此操作。

$ tr '\n' ' ' < file
variable1=test1 variable2=test2

$ var="$(tr '\n' ' ' < file)"

$ echo "$var"
variable1=test1 variable2=test2

关于bash - Shell脚本逐行读取一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14201816/

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