Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting lines into one

Tags:

linux

awk

could you please help to merge line in input file and produce output as below in descending order.

inputfile.txt

TerminalA/admin#
   51% used 
TerminalB/admin#
   62% used
TerminalC/admin#
   42% used

outputfile should contain as below in one line each terminal.

TerminalB/admin# 62% used
TerminalA/admin# 51% used
TerminalC/admin# 42% used

Below is code what I tried:

awk -f process1.awk | sort -t: -k1,2rn > output.txt

where awk script is:

$ cat process1.awk
/^$/  { print " " }
!/^$/ { printf("%s ",$0) }
like image 586
anukalps Avatar asked Aug 29 '26 12:08

anukalps


1 Answers

With your shown samples please try following awk code.

awk '{sub(/\r$/,"")} FNR%2==0{print val OFS $0 | "sort -nrk2";next} {val=$0}' Input_file

OR: In case you want to remove extra spaces before % line, which I think should be removed as per shown samples then try following:

awk '
{sub(/\r$/,"")}
FNR%2==0{
  sub(/^ +/,"")
  print val OFS $0
  next
}
{
  val=$0
}
' Input_file | sort -nrk2

Explanation:

  • Checking condition FNR%2==0 to see if line number is even then do following.
  • Printing variable val value followed by OFS followed by $0(current line).
  • using | "sort -nrk2" to further is basically sorting output in reverse/increasing order of 2nd column.
  • next will skip all further statements from here.
  • Statement {val=$0} will store current line's value into variable val. This statement will Only be executed when its an odd line number.
like image 175
RavinderSingh13 Avatar answered Aug 31 '26 06:08

RavinderSingh13



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!