繁体   English   中英

从数组写入文件bash和换行

[英]Writing from an array to a file bash and new lines

我正在尝试编写脚本以生成Pashua的模板文件(用于在OSX上创建GUI的Perl脚本)

我想为数组中的每个项目创建一个实例,因此理想的输出为:

AB1.type = openbrowser
AB1.label = Choose a master playlist file
AB1.width=310
AB1.tooltip = Blabla filesystem browser

AB2.type = openbrowser
AB2.label = Choose a master playlist file
AB2.width=310
AB2.tooltip = Blabla filesystem browser

...依次类推:

我现在用来写文本文件的是:

count=1
saveIFS="$IFS"
IFS=$'\n'
array=($(<TEST.txt))
IFS="$saveIFS"
for i in "${array[@]}"; do declare AD$count="$i"; ((count++)); done
for i in "${array[@]}"; do echo "AD$count".type = openbrowser "AD$count".label = Choose   a master playlist file \n "AD$count".width=310 \n "AD$count".tooltip = Blabla filesystem browser \n" >> long.txt; done 

但是\\ n不会在文本文件中产生换行符,并且我很确定有很多更好的方法可以做到这一点,想法?

您的第一个for循环会创建一堆您永远不会使用的变量。 您的第二个for循环在每次迭代中都执行完全相同的操作,因为它实际上并不使用$ i或您创建的任何$ ADn变量。

由于您还没有显示文本文件中的内容,因此很难知道您要完成什么,但这是一个障碍:

count=1
saveIFS="$IFS"
IFS=$'\n'
array=($(<TEST.txt))
IFS="$saveIFS"
for i in "${array[@]}"
do
    echo "AB${count}.type = openbrowser"
    echo "AB${count}.label = Choose a master playlist file"
    echo "AB${count}.width=310"
    echo "AB${count}.tooltip = Blabla filesystem browser"
    echo "some text with a line from the file: $i"
    (( count++ ))
done >> long.txt

但是,如果您正在执行类似的操作,则不需要数组:

count=1
while read -r i
do
    echo "AB${count}.type = openbrowser"
    echo "AB${count}.label = Choose a master playlist file"
    echo "AB${count}.width=310"
    echo "AB${count}.tooltip = Blabla filesystem browser"
    echo "some text with a line from the file: $i"
    (( count++ ))
done < TEST.txt >> long.txt

从此处文档中读取替换扩展计数变量i

# Your array 
a=(1 2 3 4 5 10)

for i in ${a[@]}; do cat <<EOF
AB${i}.type = openbrowser
AB${i}.label = Choose a master playlist file
AB${i}.width=3${i}0
AB${i}.tooltip = Blabla filesystem browser

EOF
done

要在echo ,语句中使用转义字符,必须使用echo -e 因此,您的代码应如下所示:

for i in "${array[@]}"; do echo -e "AD$count".type = openbrowser "AD$count".label = Choose   a master playlist file \n "AD$count".width=310 \n "AD$count".tooltip = Blabla filesystem browser \n" >> long.txt; done 

最干净的方法可能是使用heredoc:

cat << EOF > out.txt
line 1
line 2
EOF

暂无
暂无

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

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