0

I have a file like this:

1
22
1
4
$3
3
5556
$33
$233
$1
5

I want to move all the lines starting with $ to the previous line by replacing the newline characters with a space. My result should look something like:

1
22
1
4 $3
3
5556 $33 $233 $1
5

How can I do it using sed or grep or awk?

2

A similar question is posted here: SED command to format text file

As the comment of Stéphane suggest the solution to your question using sed would be as follow:

sed -e :a -e '$!N;s/\n\$/ $/;ta' -e 'P;D' filename
  • I tried this, but all that happens is a space gets inserted before lines with $. It's not working. – user199046 Dec 1 '16 at 12:00
  • 2
    @user110327, is it possible that your file be formatted as a MS-DOS text file with CRLF line delimiters? Try dos2unix < filename | sed... to see if that makes a difference. – Stéphane Chazelas Dec 1 '16 at 12:32
0

Try this:

awk 'BEGIN {ORS = " "} {print}' file | sed 's/\( \)\([0-9]\)/\n\2/g'

awk changes the column into a row by setting the Output Field Separator to a space, while sed finds the space+number pattern and replaces it with a newline+number pattern.

0
$ vi file
:g/^\$/-1j
:x

I.e. do a one-line :join on the lines which precede dollar sign lines, then save and quit.

Your Answer

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