gpt4 book ai didi

Linux - 将制表符分隔转换为管道分隔并删除前导和尾随空格

转载 作者:太空宇宙 更新时间:2023-11-04 12:24:09 24 4
gpt4 key购买 nike

我想根据以下要求将平面数据文件转换为新文件:

1) Change tab delimited to pile delimited "|".

2) Remove any leading and trailing SPACE on each "column".

3) Some columns are NULL, I want to keep the null. e.g., A||B. (2nd column is null.)

示例:

原始文件(test.dat)有一行制表符分隔的数据,共7列,“NY”后2列为NULL:

 A  New York    NY          Meal - Seafood       Grocery Department   

请注意某些字段有前导/尾随空格:

(" A ", "Meal - Seafood   ", "  Grocery Department   ")

这是我想要在新文件中的最终版本:

A|New York|NY|||Meal - Seafood|Grocery Department

Can any one write a sample code or shell script that I can use in Linux to ouput a new file?

谢谢!

最佳答案

posix 字符类 [[:space:]] 并且您可以使用 * 来匹配零个或多个空格。文字 \t 匹配制表符。喜欢,

$ sed "s/^[[:space:]]*//" test.dat | sed "s/[[:space:]]*\t[[:space:]]*/|/g" \
| sed "s/[[:space:]]*$//"
A|New York|NY|Meal - Seafood|Grocery Department

$ cat test.dat
A New York NY Meal - Seafood Grocery Department

关于Linux - 将制表符分隔转换为管道分隔并删除前导和尾随空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45202851/

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