这让我疯了......
我有一个文件BookDB.txt
,它以下列格式存储数据:
Python for dummies:Pauline:10.45:4:3
Python for dummies:Peter:10.67:0:11
C++ for dummies:Jared Loo:10.56:1:9
我想通过使用此命令将(:)分隔符替换为(/ t)来打印所有书籍的库存摘要:
sed 's/:/\t/g' cat BookDB.txt)
但它只是简单地将所有行连接成两行,如下所示:
Title Author Price Qty Avail Qty Sold Total Sales
---------------------------------------------------------------------------------------------------
Python for dummies Pauline 10.45 4 3 Python for dummies Peter 10.67 0 11 C++ for dummies Jared Loo 10.56 1 9
Python for dummies Pauline 10.45 4 3 Python for dummies Peter 10.67 0 11 C++ for dummies Jared Loo 10.56 1 9
基本上,我希望我的输出看起来像这样:
Title Author Price Qty Avail. Qty Sold
-------------------------------------------------------------------------------------------
Python for dummies Pauline 10.45 4 3
Python for dummies Peter 10.67 0 11
C++ for dummies Jared Loo 10.56 1 9
除了修改上面列出的sed命令之外,还有更好的方法来实现这个目标吗?
答案 0 :(得分:4)
BookDB.txt的内容:
Python for dummies:Pauline:10.45:4:3
Python for dummies:Peter:10.67:0:11
C++ for dummies:Jared Loo:10.56:1:9
命令:
column -ts : <(echo Title:Author:Price:Qty Avail.:Qty Sold) BookDB.txt | sed "1{p;s/./-/g}"
输出:
Title Author Price Qty Avail. Qty Sold
----------------------------------------------------------
Python for dummies Pauline 10.45 4 3
Python for dummies Peter 10.67 0 11
C++ for dummies Jared Loo 10.56 1 9
答案 1 :(得分:1)
有像
这样的输入Title:Author:Price:Qty Avail.:Qty Sold
Python for dummies:Pauline:10.45:4:3
Python for dummies:Peter:10.67:0:11
C++ for dummies:Jared Loo:10.56:1:9
您可以使用
格式化它column -t -s : your_file.txt
输出:
Title Author Price Qty Avail. Qty Sold
Python for dummies Pauline 10.45 4 3
Python for dummies Peter 10.67 0 11
C++ for dummies Jared Loo 10.56 1 9
对于没有标题的原始文档,您只需执行
即可(echo 'Title:Author:Price:Qty Avail.:Qty Sold'; cat your_file.txt) | column -t -s :
它会产生相同的输出。
您还可以添加一个sed命令来插入水平线:
< | sed '2s|^|---------------------------------------------------------------\n|'
输出:
Title Author Price Qty Avail. Qty Sold
---------------------------------------------------------------
Python for dummies Pauline 10.45 4 3
Python for dummies Peter 10.67 0 11
C++ for dummies Jared Loo 10.56 1 9
与sed类似:
... | awk 'NR == 2 { print "-----..." } 1'
... | awk 'NR == 2 { $0 = "-----..." RS $0 } 1'
... | awk 'NR == 2 { $0 = "-----...\n" $0 } 1'
答案 2 :(得分:0)
我假设你已经从你的sed
命令中遗漏了一些字符,并且它在现实中看起来更像sed 's/:/\t/g' <<<$(cat BookDB.txt)
(虽然这很奇怪,但是您发布的最少编辑版本的结果与您声称的结果类似。
如果您只是使用sed 's/:/\t/g' BookDB.txt
它是否有效?