Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve new lines while printing to a text file in shell?

Tags:

shell

awk

I have to print out some values in a txt file. they are of the following format

input="Sno;Name;Field1;Field2"

However the output must be:

Sno-Name
FIELDS ALLOCATED:
Field1
Field2

I do it like so:

 echo $input | $(awk -F';' '{print $1"-"$2}') >>$txtfile
 echo "FIELDS ALLOCATED:">>$txtfile
 echo "$input" | cut -d';' -f 3,4 >>$txtfile 

This is easy. However, the problem is that Field1 or Field2 can contain new lines. Whenever this happens, the cut or awk doesn't read the field number 4 and treats it as a new line. Do help how can I print the two fields (with new lines preserved) from the given input format.

like image 643
CoderBC Avatar asked Nov 18 '25 07:11

CoderBC


1 Answers

If the input is well-formed, you can collect input lines until you have four fields.

awk -F ';' 'r { $0 = r ORS $0 }
    NR<4 { next }
    {   print $1 "-" $2
        print "FIELDS ALLOCATED:"
        print $3; print $4
        print ""; r="" }' file
like image 169
tripleee Avatar answered Nov 20 '25 04:11

tripleee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!