Search word starting with '-', if next word does not start with same pattern then keep it in same line, else move it to new line

Viewed 44

I have a text file which contains bunch of strings as shown below.

-V -am line+tgl -am assert -debug+all -zdb -fcs_assert off 

I want to search for string starting with pattern '-' and check if the next word starts with '-'. If it does then move it to next line, else keep it in the same line.

Expected output:

-V
-am sqr+tgl
-am assert
-debug+all
-zdb
-fcs_assert off

I tried replacing space with next line character and lines which don't start with '-' append it to previous line. I am unable to figure out the second half of this approach.

cat ins.tmp/cmd.vcs | sed 's/ /\n/g' 
3 Answers

Replace a space followed by a dash by a newline followed by a dash.

sed 's/ -/\n-/g' file

You may use this awk solution:

awk -F ' +-' -v OFS='\n-' '{$1=$1} 1' file

-V
-am line+tgl
-am assert
-debug+all
-zdb
-fcs_assert off

Another option specifying the row separator RS to one or more spaces followed by -

Prepend a hyphen starting from the second row on, so that there has been at least one match for the row separator.

awk -v RS=" +-" '{print (NR==1 ? $0 : "-"$0)}' file

Output

-V
-am line+tgl
-am assert
-debug+all
-zdb
-fcs_assert off 
Related