【问题标题】:How to append space before match pattern in bash如何在bash中的匹配模式之前附加空格
【发布时间】:2014-12-09 20:30:42
【问题描述】:

如何在 bash 中使用 sed 命令在匹配模式之前或之后逐行追加空格数?

文件.txt

str_len: equ $ - str    ; calcs length of string (bytes) by
          ; subtracting this address ($ symbol)

output.txt

str_len: equ $ - str    ; calcs length of string (bytes) by
                        ; subtracting this address ($ symbol)

【问题讨论】:

    标签: regex bash sed


    【解决方案1】:

    只有一个来自 unix-magic-set-of-wondrous-things 的工具可以完全满足您的需求:

    $ column -t -s ';' -o ';' <input>
    str_len: equ $ - str    ; calcs length of string (bytes) by
                            ; subtracting this address ($ symbol)
    

    除此之外,sed 是图灵完备的,图灵的机器也是如此。但这并不意味着人们有时间在此类架构上实施非平凡解决方案:D

    编辑:上面的命令是使用column from util-linux 2.25.2 运行的,带有标志:

    -o, --output-separator string
       Specify the columns delimiter for table output (default is two spaces).
    
    -s, --separator separators
       Specify the possible input item delimiters (default is whitespace).
    
    -t, --table
       Determine  the  number  of  columns  the input contains and create a table.
       Columns are delimited with whitespace, by default, or with  the  characters
       supplied  using  the --output-separator option.  Table output is useful for
       pretty-printing.
    

    【讨论】:

    • 虽然我在某些手册中没有看到-o +1 以选择正确的工具。
    • @j.a.感谢您的评论。我已添加参考。
    【解决方案2】:

    这是使用 awk 的一种方法:

    $ awk -F' *;' -vOFS=\; '{print $1 substr("                        ",1,24-length($1)),$2}' file.txt
    str_len: equ $ - str    ; calcs length of string (bytes) by
                            ; subtracting this address ($ symbol)
    

    将输入字段分隔符设置为任意数量的空格,后跟分号。将输出字段分隔符设置为分号。打印第一列,然后是填充到 24 个字符所需的空格,然后是第二列。

    【讨论】:

      猜你喜欢
      • 2014-08-05
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多