Write the Lines back from file in Linux

root@k8-master:~/textprocess# cat employee.txt 
100  Thomas  Manager    Sales       $5,000
200  Jason   Developer  Technology  $5,500
300  Sanjay  Sysadmin   Technology  $7,000
400  Nisha   Manager    Marketing   $9,500
500  Randy   DBA        Technology  $6,000


tac : Opposite of cat command, pretty easy to reverse the line


root@k8-master:~/textprocess# tac employee.txt 
500  Randy   DBA        Technology  $6,000
400  Nisha   Manager    Marketing   $9,500
300  Sanjay  Sysadmin   Technology  $7,000
200  Jason   Developer  Technology  $5,500
100  Thomas  Manager    Sales       $5,000

Sed Command

Method 1 :

root@k8-master:~/textprocess# sed ‘1!G;h;$!d’ employee.txt 
500  Randy   DBA        Technology  $6,000
400  Nisha   Manager    Marketing   $9,500
300  Sanjay  Sysadmin   Technology  $7,000
200  Jason   Developer  Technology  $5,500
100  Thomas  Manager    Sales       $5,000

h : Copy pattern space contents to hold space.
G: Append hold space content to pattern space.
T: To skip the remaining part.


See more 


Method 2 :

root@k8-master:~/textprocess# sed -n ‘1{h;T;};G;h;$p;’ employee.txt 
500  Randy   DBA        Technology  $6,000
400  Nisha   Manager    Marketing   $9,500
300  Sanjay  Sysadmin   Technology  $7,000
200  Jason   Developer  Technology  $5,500
100  Thomas  Manager    Sales       $5,000

– See more 


AWK command

root@k8-master:~/textprocess# awk ‘{a[i++]=$0}END{for(j=i-1;j>=0;j–)print a[j];}’ employee.txt 
500  Randy   DBA        Technology  $6,000
400  Nisha   Manager    Marketing   $9,500
300  Sanjay  Sysadmin   Technology  $7,000
200  Jason   Developer  Technology  $5,500
100  Thomas  Manager    Sales       $5,000

nl command

root@k8-master:~/textprocess# nl employee.txt | sort -nr | cut -f 2-
500  Randy   DBA        Technology  $6,000
400  Nisha   Manager    Marketing   $9,500
300  Sanjay  Sysadmin   Technology  $7,000
200  Jason   Developer  Technology  $5,500
100  Thomas  Manager    Sales       $5,000

grep command

root@k8-master:~/textprocess# grep -n “” employee.txt | sort -r -n | gawk -F : “{ print $2 }”
5:500  Randy   DBA        Technology  $6,000
4:400  Nisha   Manager    Marketing   $9,500
3:300  Sanjay  Sysadmin   Technology  $7,000
2:200  Jason   Developer  Technology  $5,500
1:100  Thomas  Manager    Sales       $5,000