【发布时间】:2019-06-25 22:12:34
【问题描述】:
我想使用 bash 将多行合并为文件中的一行。我尝试了几乎所有提到的选项: How do I remove newlines from a text file? 但没有运气,也没有删除新行。此文件是来自 REST API 并使用 bash 解析的 JSON 输出。
如何将下面的行合并为 1 行?
文件内容(实际):
{"key":"HAM-5765","status":"Closed","components":"Web UX","affectedVersions":"ZCS 8.8.x","fixVersions":"Konrad-Zuse-8.8.10","customerFacingInfo":"[https://bug.rectify?id=35231 Bug 35231]
* GetEffectiveRightsRequest failed when a delegated admin could not read zimbraMailHost ([https://bug.rectify?id=108536 Bug 108536])
* Had been unable to remove \"Dynamic Group\" from distribution properties page ([https://bug.rectify?id=108499 Bug 108499])
* After performing a bulk migration, the Delegated Admin user encountered an `HTTP Error 403` when attempting to download the list of provisioned accounts
文件内容(预期):
{"key":"HAM-5765","status":"Closed","components":"Web UX","affectedVersions":"ZCS 8.8.x","fixVersions":"Konrad-Zuse-8.8.10","customerFacingInfo":"[https://bug.rectify?id=35231 Bug 35231] * GetEffectiveRightsRequest failed when a delegated admin could not read zimbraMailHost ([https://bug.rectify?id=108536 Bug 108536])* Had been unable to remove \"Dynamic Group\" from distribution properties page ([https://bug.rectify?id=108499 Bug 108499])* After performing a bulk migration, the Delegated Admin user encountered an `HTTP Error 403` when attempting to download the list of provisioned accounts
尝试了这些不同的命令:
tr -d "\n\r" < yourfile.txt
tr -d '\n' < file.txt
perl -0777 -pe 's/\n+//g' input >output
awk '/[0-9]+/ { a = a $0 ";" } END { print a }' file.txt
perl -p -i -e 's/\R//g;' filename
head -n 1 filename | od -c
perl -pe 's/\s+//g' yourfile.txt
【问题讨论】:
-
究竟是什么不起作用?
td -d '\n\r'应该可以工作。有没有可能,您希望文件内容发生变化?所有这些命令都将处理后的文件写入标准输出。您必须将该输出重定向到一个新文件中:tr -d '\n\r' < inputfile > outputfile. -
它没有删除新行。我试过 tr -d '\n\r' outputfile 它只是在输出文件中移动了一行。
-
我既不能复制也不能相信。
tr -d '\n\r' < inputfile | wc -l的输出是什么?我假设它是0。如果是这样,您是否正在使用带有自动换行的编辑器查看文件?请不要使用硬盘驱动器上的文件,而是复制此问题中的示例,以确保我们使用相同的输入。如果它适用于您的示例但不适用于您的实际文件,则发布您的文件的 hexdump。 -
使用效果很好: echo -e "${jsonOutput}" >> ${releaseNoteFile} rm -f ${releaseNoteDir}/ReleaseNote.tmp tr -d '\n\r' ${releaseNoteDir}/ReleaseNote.tmp mv ${releaseNoteDir}/ReleaseNote.tmp ${releaseNoteFile} 请作为答案发布,以便我接受。谢谢索科维!
-
不清楚您的问题是什么,或者@Socowi 的 cmets 如何引导您发出您所说的解决问题的命令。如果您真正的问题是“我怎样才能用修改后的文件替换原始文件”,那么有很多重复的。
标签: bash