我有一个我写的 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/