0

I have text file (test.txt) that looks exactly like this (same number of options for every instance):

# 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 \

I want to reorganize the text so it looks like this:

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
2
  • Hello, @Nadal do you have the same number of options ever every line?
    – user88036
    Oct 9 '18 at 11:04
  • Why is "first" supposed to join with "a comment"? There is no trailing backslash on the comment line. Oct 9 '18 at 14:35
2

With a single sed program:

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 is pretty compact though: read paragraphs (-00) and replace leading whitespace and comment chars for each line in the paragraph (the /m and /g modifiers), and remove trailing backslash-newline.

perl -00 -lanE 's/^\s*#*\s*//mg; s/\\(?:\Z|\n)/ /g; say' test.txt
0
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 replaces # with empty spaces and ^ matches for the # position within the strings. Then sed s/\\/ /g' replaces backslashes \ with empty spaces.

xargs lines up and creates equal white spaces between the words.

finally, sed adds new lines after every word "option3"

1
  • 1
    use s/\\$/ /g and 's/\n//g' is redundant and you have used xargs to do so. and can you provide better way to solve with out hard-coding option3.
    – Devidas
    Oct 9 '18 at 11:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy