删除多余的符号并调整线条

删除多余的符号并调整线条

我有看起来与此完全相同的文本文件(test.txt)(每个实例的选项数量相同):

# a comment

first: info about first:  option1 \
                          option2 \
                          option3

second: info about second: option1 \
  option2 \
  option3

#third: info about third: option1 \
#                         option2 \
#                         option3

fourth: info about fourth: option1 \
                           option2 \
                           option3 \

我想重新组织文本,使其看起来像这样:

a comment first: info about first: option1 option2 option3 
second: info about second: option1 option2 option3 
third: info about third: option1 option2 option3 
fourth: info about fourth: option1 option2 option3

答案1

使用单个 sed 程序:

sed -E '
    # remove leading comment chars
    s/^[[:blank:]]*#+[[:blank:]]*//

    # label "a" for branching
    :a
    # if trailing slash:
    /\\$/ {
        # read next line
        N
        # remove backslash, newline, leading whitespace and comment char 
        s/\\\n[[:blank:]]*#*[[:blank:]]*/ /
        # branch to label "a"
        ba
    }

    # remove blank lines
    /^[[:blank:]]*$/d
' test.txt

不过,Perl 相当紧凑:读取段落 ( -00) 并替换段落中每一行的前导空格和注释字符(/m/g 修饰符),并删除尾随的反斜杠换行符。

perl -00 -lanE 's/^\s*#*\s*//mg; s/\\(?:\Z|\n)/ /g; say' test.txt

答案2

sed 's/^#/ /g;s/\\/ /g' file | xargs | sed 's/option3 /option3 \n/g'

a comment first: info about first: option1 option2 option3 
second: info about second: option1 option2 option3 
third: info about third: option1 option2 option3 
fourth: info about fourth: option1 option2 option3

sed 's/^#/ /g替换#为空格并^匹配#字符串中的位置。然后用空格sed s/\\/ /g'替换反斜杠。\

xargs排列并在单词之间创建相等的空白。

最后,sed在每个单词“option3”后添加新行

相关内容