gpt4 book ai didi

Print variables read from file to file without newline(打印从一个文件读取到另一个文件的变量,不带换行符)

转载 作者:bug小助手 更新时间:2023-10-28 13:13:45 25 4
gpt4 key购买 nike



I am reading in a list of variables, then manipulating them, then printing them to file in various formats. But the variables come with a newline, and nothing in my bash arsenal can touch it.

我正在读取变量列表,然后操作它们,然后以各种格式将它们打印到文件中。但变量有一个换行符,我的bash武器库中没有任何东西能与之相提并论。


Here is input.txt:

Input.txt如下:


1
2
3

The bash script:

Bash脚本:


echo -n "" > output.txt
while read p; do
echo -n ${p} | xargs >> output.txt
done <input.txt

I don't want there to be any newlines in output.txt, I want it to be:

我不希望output.txt中有任何换行符,我希望它是:


123

But it's:

但它是:


1
2
3

With a \r\n plaguing each line. How can I remove them?

每一行都有一个\r\n困扰。我怎么才能去掉它们呢?


更多回答

tr -d '\r\n' < input.txt > output.txt

Tr-d‘\r\n’output.txt

The line breaks are being added by xargs, so just remove it from the pipeline. Also, echo -n is unreliable; use printf '%s' "${p}" instead. And there's no reason to redirect each command to the output file separately; just remove the first echo -n "" and the redirect within the loop, and add >output.txt after the done.

换行符是由xargs添加的,因此只需将其从管道中删除即可。另外,ECHO-n是不可靠的;请改用printf‘%S’“${p}”。而且没有理由将每个命令分别重定向到输出文件;只需删除循环中的第一个ECHO-n“”和重定向,并在Done之后添加>output.txt。

Shellcheck identifies several problems with the code. The report includes links to more information about the problems and how to fix them. It's a good idea to run Shellcheck on all new and modified shell code.

Shellcheck发现了代码中的几个问题。该报告包含指向有关问题以及如何修复这些问题的详细信息的链接。对所有新的和修改过的外壳代码运行shellcheck是个好主意。

@Shawn This is a simplification, the question says that he's processing the values after reading them, not just writing directly from the input to the output.

@Shawn这是一个简化,问题是他在读取值之后处理它们,而不仅仅是直接从输入写到输出。

Use dos2unix to remove \r characters from the file before processing it. read will remove the newlines when reading the line.

在处理文件之前,使用dos2unix从文件中删除\r字符。读取行时,READ将删除换行符。

优秀答案推荐

One way to remove the carriage returns is to add that character to IFS when reading lines from the file:

删除回车的一种方法是在从文件中读取行时将该字符添加到IF中:


IFS+=$'\r'
while read -r line; do
# do stuff with $line
printf '%s' "$line"
done < input.txt > output.txt

更多回答

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