Split or merge strings in Linux with sed

I have a file that contains information below

$ cat test.txt 
Studentename:Ram
rollno:12
subjects:6
Highest:95
Lowest:65
Studentename:Krish
rollno:13
subjects:6
Highest:90
Lowest:45
Studentename:Sam
rollno:14
subjects:6
Highest:75
Lowest:65

I am trying to post information about one student in solitary. ie My conclusion should be

Studentename:Ram rollno:12 subjects:6 Highest:95 Lowest:65
Studentename:Krish rollno:13 subjects:6 Highest:90 Lowest:45
Studentename:Sam rollno:14 subjects:6 Highest:75 Lowest:65.

Below is the command I wrote

cat test.txt | tr "\n" " " | sed 's/Lowest:[0-9]\+/Lowest:[0:9]\n/g'

The above command is the interrupt line in regex Lowest: [0-9], but it does not print the pattern. Instead, it prints Lowest: [0-9].

Please, help

+4
source share
4 answers

Try:

$ sed '/^Studente/{:a; N; /Lowest/!ba; s/\n/ /g}' test.txt
Studentename:Ram rollno:12 subjects:6 Highest:95 Lowest:65
Studentename:Krish rollno:13 subjects:6 Highest:90 Lowest:45
Studentename:Sam rollno:14 subjects:6 Highest:75 Lowest:65

How it works

/^Studente/{...}tells sed to execute commands inside braces only on lines starting with Studente. These commands are:

  • :a

    This defines the label a.

  • N

    This is read on the next line and adds it to the template space.

  • /Lowest/!ba

    Lowest, sed a.

    /Lowest/ true, Lowest. sed ! , /Lowest/! is true if the line does not contain . In ba , the b stands for the branch command and a` - .

  • s/\n/ /g

    sed, .

+2

:

awk '{if ($1 !~ /^Lowest/) {printf "%s ", $0} else {print}}' file.txt

, :

awk '$1!~/^Lowest/{printf"%s ",$0;next}1' file.txt

:

tr "\n" " " < file.txt | sed 's/Lowest:[0-9]\+/&\n/g'

: & - ,

+2

GNU sed, , - :

sed ':a; N; /\nStudent/{P; D}; s/\n/ /; ba' test.txt
+2

(GNU sed):

sed '/^Studentename:/{:a;x;s/\n/ /gp;d};H;$ba;d' file

, .

0

Source: https://habr.com/ru/post/1693557/


All Articles