Add or Insert a Heading Extra Line after Every nth Line of File in Unix / Linux


Here is my input data file and see the output as per the requirements below.
cat inp.txt
clark            2450
king             5000
miller           1300
smith             800

jones            2975
scott            3000
adams            1100


  1. Add extra line to every line

awk '{$0 = $0"\n"} 1' inp.txt
awk '{$0 = $0"\n"} { print }' inp.txt
clark            2450

king             5000

miller           1300

smith             800

jones            2975

scott            3000

adams            1100

  1. Add Extra line after every 2 lines. You can change the value of 2 which is marked in red below as per your requirement. Suppose if you wanted to add a new line after 3 you can use 3 instead of 2 in below example.

awk '!( NR % 2) {$0 = $0"\n"} 1' inp.txt
or
awk '!( NR % 2) {$0 = $0"\n"} { print }' inp.txt
clark            2450
king             5000

miller           1300
smith             800

jones            2975
scott            3000

adams            1100

  1. Add heading line every n lines
awk '!( NR % 2) {$0 = "Name             SAL\n---------------------\n"$0} 1' inp.txt
or
awk '!( NR % 2) {$0 = "Name             SAL\n---------------------\n"$0} { print }' inp.txt
clark            2450
Name             SAL
-------------------
king             5000
miller           1300
Name             SAL
-------------------
smith             800
jones            2975
Name             SAL
-------------------
scott            3000
adams            1100


  1. Add Column titles to every lines
awk  '{print "Name: "$1 "\t Sal:" $2}' inp.txt
Name: clark      Sal:2450
Name: king       Sal:5000
Name: miller     Sal:1300
Name: smith      Sal:800
Name: jones      Sal:2975
Name: scott      Sal:3000
Name: adams      Sal:1100

You can achieve these goals using a lengthy shell script as below.
#!/bin/sh
cntr=0
while read line
    do
    ((chk=cntr%3))
    if [ "$chk" -eq 0 ]; then
        echo -e "\n$line"
    else
        echo "$line"
    fi
    ((cntr=cntr+1))
done < inp.txt
DBA Tips Data Pump Reference

0 comments:

Post a Comment

 

dba topics. Copyright 2011-16 All Rights Reserved | Site Map | Contact | Disclaimer | Google