英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论