Home > OS >  How to swap the even and odd lines via bash script?
How to swap the even and odd lines via bash script?

Time:03-02

In the incoming string stream from the standard input, swap the even and odd lines. I've tried to do it like this, but reading from file and $i -lt $a.count aren't working:

$a= gc test.txt
for($i=0;$i -lt $a.count;$i  )
{
if($i%2)
{
$a[$i-1]
}
else
{
$a[$i 1]
}
}

Please, help me to get this working

CodePudding user response:

A pure solution that reads from stdin and writes to stdout:

#!/bin/bash

while read -r odd && read -r even
do
    echo "$even"
    echo "$odd"
    unset odd
done

# in case there are an odd number of lines in the file, print the last "odd" line read
if [[ -n $odd ]]; then
    echo "$odd"
fi

Reading from one file and writing to another:

#!/bin/bash

infile="inputfile"
outfile="outputfile"

{
while read -r odd && read -r even
do
    echo "$even"
    echo "$odd"
    unset odd
done < "$infile"

# in case there are an odd number of lines in the file, print the last "odd" line read
if [[ -n $odd ]]; then
    echo "$odd"
fi
} > "$outfile"

If you want to overwrite infile, end with:

mv "$outfile" "$infile"

CodePudding user response:

Suggesting one line awk script:

awk '!(NR%2){print$0;print r}NR%2{r=$0}' input.txt

awk script explanation

!(NR % 2){ # if row number divide by 2 witout reminder
  print $0; # print current row
  print evenRow; # print saved row
}
(NR % 2){ # if row number divided by 2 with reminder
  evenRow = $0; # save current row in variable
}
  • Related