Reverse The Order Of Lines In Bash

Find the data you need here

We provide programming data of 20 most popular languages, hope to help you!

Previous PostNext Post

How can I reverse the order of lines in a file?

foo
bar
baz
baz
bar
foo
tac a.txt > b.txt
tail -r myfile.txt
# reverse order of lines (emulates "tac")
# bug/feature in HHsed v1.5 causes blank lines to be deleted
sed '1!G;h;$!d'               # method 1
sed -n '1!G;h;$p'             # method 2
awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' file*
perl -e 'print reverse <>'
:g/^/m0
tac <file_name>
$ cat file1.txt
1
2
3
4
5

$ tac file1.txt
5
4
3
2
1
$ (tac 2> /dev/null || tail -r)
grep -n "" myfile.txt | sort -r -n | gawk -F : "{ print $2 }"
function print_reversed {
    local lines i
    readarray -t lines

    for (( i = ${#lines[@]}; i--; )); do
        printf '%s\n' "${lines[i]}"
    done
}

print_reversed < file
brew install coreutils
sudo apt-get update
sudo apt-get install coreutils 
echo "alias tac='gtac'" >> ~/.bash_aliases (or wherever you load aliases)
source ~/.bash_aliases
tac myfile.txt
gawk '{ L[n++] = $0 } 
  END { while(n--) 
        print L[n] }' file
$ cat order.txt
roger shah 
armin van buuren
fpga vhdl arduino c++ java gridgain
$ tac order.txt > inverted_file.txt
$ cat inverted_file.txt
fpga vhdl arduino c++ java gridgain
armin van buuren
roger shah 
seq 1 10 | sort -R | tee /tmp/lst |cat <(cat /tmp/lst) <(echo '-------') **...**
seq 1 10 | sort -R | tee /tmp/lst |cat <(cat /tmp/lst) <(echo '-------') \
<(tac)
seq 1 10 | sort -R | tee /tmp/lst |cat <(cat /tmp/lst) <(echo '-------') \
<(python -c "import sys; print(''.join(([line for line in sys.stdin])[::-1]))")
sed -i '1!G;h;$!d' filename
$tac file > file2
$sed -i '1!G;h;$!d' file
$diff file file2
$
awk '{arr[i++]=$0} END {while (i>0) print arr[--i] }' filename
cat dax-weekly.csv | awk '1 { last = NR; line[last] = $0; } END { print line[1]; for (i = last; i > 1; i--) { print line[i]; } }'
tail -n20 file.txt | tac
# Generate a newline delimited sequence of 1 to 10
$ seq 10
1
2
3
4
5
6
7
8
9
10

# Use - to read from stdin.
# vim has a delay and annoying 'Vim: Reading from stdin...' output
# if you use - to read from stdin. Use --not-a-term to hide output.
# --not-a-term requires vim 8.0.1308 (Nov 2017)
# Use -E for improved ex mode. -e would work here too since I'm not
# using any improved ex mode features.
# each of the commands I explained above are specified with a + sign
# and are run sequentially.
$ seq 10 | vim - --not-a-term -Es +'g/^/m0' +'%p' +'q!'
10
9
8
7
6
5
4
3
2
1
# non improved ex mode works here too, -e.
$ seq 10 | vim - --not-a-term -es +'g/^/m0' +'%p' +'q!'

# If you don't have --not-a-term, use /dev/stdin
seq 10 | vim -E +'g/^/m0' +'%p' +'q!' /dev/stdin

# POSIX compliant (maybe)
# POSIX compliant ex doesn't allow using + sign to specify commands.
# It also might not allow running multiple commands sequentially.
# The docs say "Implementations may support more than a single -c"
# If yours does support multiple -c
$ seq 10 | ex -c "execute -c 'g/^/m0' -c '%p' -c 'q!' /dev/stdin

# If not, you can chain them with the bar, |. This is same as shell
# piping. It's more like shell semi-colon, ;.
# The g command consumes the |, so you can use execute to prevent that.
# Not sure if execute and | is POSIX compliant.
seq 10 | ex -c "execute 'g/^/m0' | %p | q!" /dev/stdin
#!/usr/bin/env sh

vim - --not-a-term -Es "[email protected]" +'%p | q!'
seq 10 | ved +'g/^/m0'
#!/usr/bin/env sh

vim -E "[email protected]" +'%p | q!' /dev/stdin
rev
text here
rev <file>
rev texthere
sort -r < filename
rev < filename

How to reverse the order of lines?

rat
ox
tiger
⋮
dog
pig
pig
dog
⋮
tiger
ox
rat
:g/^/exe "normal ddggP"
:g/^/move 0
:command! -bar -range=% Reverse <line1>,<line2>global/^/m<line1>-1
:g/^/m0
:%!tac                                                                                                                                                                                                                                                              
:%!tail -r
:call setline(1, reverse(getline(1, line('$'))))
:command! -bar -range=% Reverse call setline(<line1>, reverse(getline(<line1>, <line2>)))
:global/^/m 0
:g/^/m 0
:'t+1,.g/^/m 't
 :13,13+4g/^/m12

Reverse order of lines

:g/^/m0
:100,150g/^/m99
:%!tac
:100,150!tac
command! -bar -range=% Reverse <line1>,<line2>g/^/m0|nohl
" REVERSE line ordering, and move those lines to the top of the file.
command! -bar -range=% Reverse <line1>,<line2>g/^/m<line1>-1|nohl

Hello Earth
Hello Mars
Mars Hello Earth Hello
Earth Hello
Mars Hello
one two 
four five
two one
five four
#!/bin/bash
text=$(cat $1)
arr=($text)
al=${#arr[@]}
let al="al-1"

while (($al >= 0))
do
    echo -n "${arr[al]}"
    echo -n " "
    let al="al - 1"
done

echo
$ awk '{for(i=NF;i>=1;i--) printf "%s ", $i;print ""}' input.txt                                                  
Earth Hello 
Mars Hello 
$ python -c "import sys;print '\n'.join([ ' '.join(line.split()[::-1]) for line in sys.stdin ])"  < input.txt     
Earth Hello
Mars Hello
#!/bin/bash

while IFS= read -r line
do
     bash -c 'i=$#; while [ $i -gt 0 ];do printf "%s " ${!i}; i=$(($i-1)); done' sh $line   
     echo 
done < input.txt
$ ./reverse_words.sh                                                                                              
Earth Hello 
Mars Hello 
while IFS= read -r line
do
   # some code
done < text.txt
bash -c 'i=$#; while [ $i -gt 0 ];do printf "%s " ${!i}; i=$(($i-1)); done' sh $line
#!/bin/bash

while IFS= read -r line
do
     var=$(tac -s " " <<< "$line" )
     echo  $var
done < input.txt
$ cat input.txt                                                                                                   
Hello Earth end of line
Hello Mars  another end of line
abra cadabra magic
$ ./reverse_words.sh                                                                                              
line of end Earth Hello 
line of end another Mars Hello 
magic cadabra abra 
$ python -c "import sys;print '\n'.join([ ' '.join(line.split()[::-1]) for line in sys.stdin ])"  < input.txt  
line of end Earth Hello
line of end another Mars Hello
magic cadabra abra
$ awk '{for(i=NF;i>=1;i--) printf "%s ", $i;print ""}' input.txt
line of end Earth Hello 
line of end another Mars Hello 
magic cadabra abra 
$ perl -lane '@r=reverse(@F); print "@r"' input.txt                           
line of end Earth Hello
line of end another Mars Hello
magic cadabra abra


$ ruby -ne 'puts $_.chomp.split().reverse.join(" ")' < input.txt                                                  
line of end Earth Hello
line of end another Mars Hello
magic cadabra abra
awk '{print $2, $1}'
% cat bar.txt
Hello Earth
Hello Mars

% awk '{print $2, $1}' bar.txt
Earth Hello
Mars Hello
sed -r '
    # Mark the current end of the line by appending a LF character ("\n")
    G

    # Main loop: move the first word of the line just after the LF
    # and repeat until the LF is at the beginning of the line
    :loop
    s/([^[:space:]]+)(.*\n)/\2\1 /
    t loop

    # Remove remaining spaces up to the LF and the superfluous trailing space
    s/.*\n| $//g
'
sed -r 'G; :loop; s/(\S+)(.*\n)/\2\1 /; t loop; s/.*\n| $//g'
$ sed -r '...' <<< "The quick
brown fox jumps

over
the lazy dog"
quick The 
jumps fox brown 

over 
dog lazy the 
sed '
  G
  :loop
     s/\([^[:space:]]\{1,\}\)\(.*\n\)/\2\1 /
  t loop
  s/ $//
  s/.*\n//'
while read line; do echo $(echo $line | tr " " "\n" | tac); done < $1

Reverse the order of characters in a string

[[email protected] tmp]$ echo 12345 | rev
54321
var="12345"
copy=${var}

len=${#copy}
for((i=$len-1;i>=0;i--)); do rev="$rev${copy:$i:1}"; done

echo "var: $var, rev: $rev"
$ bash rev
var: 12345, rev: 54321
var="123"
rav=$(echo $var | rev)
echo $rav
$ rev <<< $'12\n34' | tail -r
43
21
$ rev <<< $'12\n34' | gtac
43
21
$ LC_CTYPE=C rev <<< あの
��め�
$ export LC_ALL=C; LC_ALL=en_US.UTF-8 rev <<< あの
のあ
var="12345"     rev=""

for(( i=0 ; i<${#var} ; i++ )); do rev="${var:i:1}$rev"; done

echo "var: $var, rev: $rev"
var=$1   len="${#var}"   i=0   rev=""

while (( i<len )); do rev="${var:i++:1}$rev"; done

echo "var: $var, rev: $rev"
var="12345"     rev=""    i=1

while  [ "$i" -le "${#var}" ]
do     rev="$(echo "$var" | awk -v i="$i" '{print(substr($0,i,1))}')$rev"
       : $(( i+=1 ))
done

echo "var: $var, rev: $rev"
a=12345
len=${#a}
for ((i=1;i<len;i++)); do a=$a${a: -i*2:1}; done; a=${a:len-1}
echo $a
for ((i=0;i<len;i++)); do a=${a:i*2:1}$a; done; a=${a:0:len}
for ((i=1;i<len;i++)); do a=${a:0:len-i-1}${a: -i:i+1}${a:len-i-1:1}; done
echo '!!!esreveR si sihT' | grep -o . | tac | tr -d '\n' ; echo

echo '!!!esreveR si sihT' | fold -w 1 | tac | tr -d '\n' ; echo
echo '!!!esreveR si sihT' | xxd -p | grep -o .. | tac | xxd -r -p ; echo

echo '!!!esreveR si sihT' | xxd -p | fold -w 2 | tac | xxd -r -p ; echo
awk -F '' '{ for(i=NF; i; i--) printf("%c", $i); print "" }'
echo "var: $var, rev: $rev"
$ rev
var: 12345, rev: 54321
echo 12345 | awk '{for (i = length($0); i > 0; i--) {printf("%s", substr($0, i, 1));} print "";}'
$ echo 123456 | sed $'s/./&\\\n/g' | sed -ne $'x;H;${x;s/\\n//g;p;}'
654321
awk 'BEGIN{FS=""} {for (i=NF; i>0; i--) s=s $i; print s}' <<< '123456'
654321
reve=`echo "$word" | awk '{for(i=length($0); i>0;i--) printf (substr($0,i,1));}'`
echo  "$reve"

Shell Programming and Scripting

awk '{x[NR] = $0}
 END { while ( NR > 0 ) print x[NR--] }' [FILENAME ...]
sed '1!G;h;$!d'    file
sed -n '1!G;h;$p' file
cat -n <filename>| sort -r | cut -f2-20 > reversedfile
 $ time tac .bashrc > /dev/null

real    0m0.021s
user    0m0.002s
sys     0m0.005s
$ time awk '{x[NR]=$0}END{while (NR) print x[NR--]}' .bashrc > /dev/null

real    0m0.010s
user    0m0.003s
sys     0m0.006s
$ time xx.sh .bashrc > /dev/null

real    0m2.060s
user    0m0.483s
sys     0m1.420s
$ cat file
Linux
Solaris
AIX
$ tac file
AIX
Solaris
Linux
$ nl file | sort -nr | cut -f 2-
AIX
Solaris
Linux
$ sed -n '1{h;T;};G;h;$p;' file
AIX
Solaris
Linux
$  awk '{a[i++]=$0}END{for(j=i-1;j>=0;j--)print a[j];}' file
AIX
Solaris
Linux
$ perl -ne 'push @arr,$_;}{print reverse @arr;' file
AIX
Solaris
Linux
$ perl -ne 'push @arr,$_;}{while(@arr){ print pop @arr;}' file
AIX
Solaris
Linux

Previous PostNext Post

Related code examples