读取并将一个txt文件输出为所需格式。

huangapple go评论82阅读模式
英文:

Read and output a txt file to a desired format

问题

🎉 the quick brown - fox jumps over - the lazy dog

英文:

I have a text file:

- the quick brown
- fox jumps over
- the lazy dog

The structure of each line is [hyphen] [space] [text].

Then I wrote this:

echo "🎉$(cat file.txt | tr "\r\n" ";" | tr -d "-")"

// 🎉 the quick brown- fox jumps over- the lazy dog

How can I format the text like below? I want to add a space before the hyphen but cannot figure out the proper method.

🎉 the quick brown - fox jumps over - the lazy dog

答案1

得分: 2

你可以使用 paste 命令,通过 -s 选项连接这些行,使用 -d 指定空格字符作为分隔符,然后使用 sed 命令替换第一个连字符:

paste -sd ' ' file.txt | sed 's/-/🎉/'
🎉 the quick brown - fox jumps over - the lazy dog
英文:

You can use paste to concatenate the lines with -s, using a space character as delimiter provided by -d, then use sed to replace the first hyphen:

paste -sd ' ' file.txt | sed 's/-/🎉/'
🎉 the quick brown - fox jumps over - the lazy dog

答案2

得分: 1

使用awk:

$ awk 'NR==1{sub(/-/,"🚩")} {printf "%s%s", sep, $0; sep=" "} END{print ""}' file
🚩 the quick brown - fox jumps over - the lazy dog
英文:

Using any awk:

$ awk 'NR==1{sub(/-/,"🎉")} {printf "%s%s", sep, $0; sep=" "} END{print ""}' file
🎉 the quick brown - fox jumps over - the lazy dog

答案3

得分: -3

要按照您描述的方式格式化文本,即在每个连字符前加一个空格,您可以稍微修改现有的命令。以下是您可以执行的操作:

echo "🎉$(sed ':a;N;$!ba;s/\n/ - /g' file.txt | tr -d "-")"

这个命令将为您提供所需的输出:

🎉 the quick brown - fox jumps over - the lazy dog
英文:

To format the text as you've described, with a space before each hyphen, you can modify your existing command slightly. Here's how you can do it:

echo "🎉$(sed ':a;N;$!ba;s/\n/ - /g' file.txt | tr -d "-")"

This command will give you the desired output:

🎉 the quick brown - fox jumps over - the lazy dog

huangapple
  • 本文由 发表于 2023年8月11日 00:44:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76877760.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定