【问题标题】:bash sort / uniq -c: how to use tab instead of space as delimiter in output?bash sort / uniq -c:如何在输出中使用制表符而不是空格作为分隔符?
【发布时间】:2016-07-12 19:13:21
【问题描述】:

我有一个文件strings.txt 列出字符串,我正在处理它:

sort strings.txt | uniq -c | sort -n > uniq.counts

因此生成的文件uniq.counts 将列出按计数升序排序的 uniq 字符串,如下所示:

 1 some string with    spaces
 5 some-other,string
25 most;frequent:string

请注意,strings.txt 中的字符串可能包含空格、逗号、分号和其他分隔符,制表符除外。我怎样才能让uniq.counts 采用这种格式:

 1<tab>some string with    spaces
 5<tab>some-other,string
25<tab>most;frequent:string

【问题讨论】:

  • 这不是关于sort 的真正问题(或者,更确切地说,更改sort 使用的分隔符既简单又显示在手册页中,如-t aka --field-separator ; 因此sort -t $'\t' 足以回答原标题中提出的全部问题);有趣的部分是如何将uniq -c 使用的分隔符更改为制表符。
  • 正如 chepner 简要评论的那样——即使在默认情况下使用 IFS,while read -r count content; do ... 也可以使用原始输出格式成功解析来自 uniq.counts 中其余输出的计数,而无需单独字符。
  • 这能回答你的问题吗? Why uniq -c output with space instead of \t?

标签: bash sorting delimiter


【解决方案1】:

你可以这样做:

sort strings.txt | uniq -c | sort -n | sed -E 's/^ *//; s/ /\t/' > uniq.counts

sed 将首先删除行首(计数前)的所有前导空格,然后将计数后的空格替换为tab 字符。

【讨论】:

    【解决方案2】:

    在写入uniq.counts 之前,您可以简单地将排序等的输出通过管道传输到sed,例如添加:

    | sed -e 's/^\([0-9][0-9]*\)\(.*$\)/\1\t\2/' > uniq.counts
    

    完整的表达式是:

    $ sort strings.txt | uniq -c | sort -n | \
    sed -e 's/^\([0-9][0-9]*\)\(.*$\)/\1\t\2/' > uniq.counts
    

    (为清楚起见,包括续行)

    【讨论】:

      【解决方案3】:

      使用 GNU sed:

      sort strings.txt | uniq -c | sort -n | sed -r 's/([0-9]) /\1\t/' > uniq.counts
      

      输出到 uniq.counts:

      1 一些带空格的字符串 5 其他,字符串 25 最;频繁:字符串

      如果您想“就地”编辑文件,请使用 sed 的选项 -i

      【讨论】:

        猜你喜欢
        • 2021-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-04
        • 2013-09-07
        • 2020-02-23
        • 2013-11-25
        • 1970-01-01
        相关资源
        最近更新 更多