Skip to content
Advertisement

changing two lines of a text file

I have a bash script which gets a text file as input and takes two parameters (Line N° one and line N° two), then changes both lines with each other in the text. Here is the code:

#!/bin/bash

awk -v var="$1" -v var1="$2" 'NR==var {
    s=$0
    for(i=var+1; i < var1 ; i++) {
        getline; s1=s1?s1 "n" $0:$0
    }
    getline; print; print s1 s
    next
}1' Ham > newHam_changed.txt 

It works fine for every two lines which are not consecutive. but for lines which follows after each other (for ex line 5 , 6) it works but creates a blank line between them. How can I fix that?

Advertisement

Answer

I think your actual script is not what you posted in the question. I think the line with all the prints contains:

print s1 "n" s

The problem is that when the lines are consecutive, s1 will be empty (the for loop is skipped), but it will still print a newline before s, producing a blank line.

So you need to make that newline conditional.

awk -v var="4" -v var1="6" 'NR==var {
    s=$0
    for(i=var+1; i < var1 ; i++) {
        getline; s1=s1?s1 "n" $0:$0
    }
    getline; print; print (s1 ? s1 "n" : "") s
    next
}1' Ham > newHam_changed.txt 
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement