linux - Shell 脚本 - 逗号后换行?

标签 linux shell line new-operator

我有一个我写的 shell 脚本,它从一个位置抓取一个名字列表,每个名字都用逗号分隔,<-- 我想知道是否有什么我可以写的来制作一个名字列表存储在文本文件中以在每个逗号后缩进到一个新行?

例如,存储在文本文件中的名称列表如下所示:

"Red", "Blue", "Green"

我希望它们看起来像这样:

Red
Blue
Green

数据是从网站的 html 代码中提取的,因此它们周围有引号和逗号,如果至少可以将它们格式化为新行,那就太好了。如果您有帮助,谢谢。

最佳答案

假设逗号分隔的日期在变量 $data 中,您可以通过将 $IFS(列表分隔符变量)设置为 ', ' 并使用 for 循环告诉 bash 拆分它:

TMPIFS=$IFS #Stores the original value to be reset later
IFS=', '

echo '' > new_file #Ensures the new file is empty, omit if the file already has contents

for item in $data; do
item=${item//'"'/} #Remove double quotes from entries, use item=${item//"'"/} to remove single quotes
echo "$item" >> new_file #Appends each item to the new file, automatically starts on a new line
done

IFS=$TMPIFS #Reset $IFS in case other programs rely on the default value

这将为您提供所需格式的输出,尽管有一个前导空行。

关于linux - Shell 脚本 - 逗号后换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8031719/

相关文章:

c - 使用 struct utimbuf 更改文件访问时间

mysql - 在 Ubuntu 14.04 中安装 MySQL 5.6 会触发删除所需的包

linux - 如何在 Telnet bash 脚本中设置超时?

c - 用 C 编写 Shell,传递给函数时消失 char**

java - 根据角度绕圆画一条线

line - 什么是反向换行

linux - 如何恢复损坏的 dnf 数据库?

c++ - isspace 宏与 locale_facets.h 中的 isspace 函数冲突

android - 无法从 python 中调用 bash

iphone - 在 iPhone 上用手指触摸绘制平滑的线条