I am trying to replace a pattern between the lines of a file.
Specifically, I would like to replace
,\n & with
, &\n in large and multiple files. This actually moves the symbol & to the previous line. This is very easy with CTR+H, but I found it difficult with sed.
So, the initial file is in the following form:
A +, & B -, & C ), & D +, & E (, & F *, # & G -, & H +, & I (, & J +,
The output-desired form is:
A +, & B -, & C ), & D +, & E (, & F *, & # & G -, H +, & I (, & J +,
Following previous answered questions on stackoverflow, I tried to convert it with the commands below:
sed ':a;N;$!ba;s/,\n &/&\n /g' file1.txt > file2.txt
sed -i -e '$!N;/&/b1' -e 'P;D' -e:1 -e 's/\n[[:space:]]*/ /' file2.txt
but they fail if the symbol "#" is present in the file.
Is there any way to replace the matched pattern simpler, let’s say:
sed -i 's/,\n &/, &\n /g' file
Thank you in advance!
$ sed ':a;N;s/\n \+\(&\) \(.*\)/ \1\n \2/;ba' input_file A +, & B -, & C ), & D +, & E (, & F *, # & G -, & H +, & I (, & J +,