shell 读取并输出一个txt文件到所需的格式

qmelpv7a  于 12个月前  发布在  Shell
关注(0)|答案(3)|浏览(150)

我有一个文本文件:

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

每条线的结构是[hyphen] [space] [text]
然后我写了这个:

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

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

我怎样才能像下面这样格式化文本?我想在连字符前加一个空格,但不知道正确的方法。

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

8gsdolmq1#

您可以使用paste将行与-s连接起来,使用空格字符作为-d提供的字符串,然后使用sed替换第一个连字符:

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

v1l68za42#

使用任何awk:

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

bogh5gae3#

要按照您所描述的设置文本的格式,在每个连字符前加一个空格,您可以稍微修改现有的命令。你可以这样做:

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

此命令将给予所需的输出:

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

相关问题