4

How can i reverse a line in a file in Order

Example :

Input file :

123
500
1000
LOAN
GOD
10000
01000

Output Format:

321
005
0001
NAOL
DOG
00001
00010
0

7 Answers 7

12

Use rev(1).

0
2
perl -lne 'print scalar reverse' < my_file.dat
1
  • Slightly terser perl -lpe '$_=reverse' <file Sep 27, 2020 at 6:15
1

There is no simple command to do that in the Single Unix Specification. If, however, you are able to go beyond what Unix provides, you can install rev or tac. In fact, one of those might very well already be installed on your system, despite the fact that they are not part of Unix.

Obviously, since they are not part of Unix, you should never depend on them being there.

1

You can use the tac command:

tac inputFile > outFile 

TAC(1)

NAME
       tac - concatenate and print files in reverse

SYNOPSIS
       tac [OPTION]... [FILE]...

DESCRIPTION
       Write each FILE to standard output, last line first.  With no FILE, or when FILE is -, read standard input.
2
  • This is the simplest solution. Apr 9, 2017 at 4:57
  • That reverses the lines in the file, not the chars on each line as clearly requested. Sep 27, 2020 at 6:16
0

perl -n -e "print reverse split //, $_"

0

It’s ugly, but you can do this in sed:

sed 's/$/\n/; :loop; s/\(.\)\(.*\n\)/\2\1/; t loop; s/\n//'

This

  • Adds an explicit newline to the end of the current line.
  • :loop is a label.
  • Takes the first character in the line and moves it to after the newline.
  • If the above succeeded, jump to the loop label and do it again.
  • Otherwise, remove the extra newline.

So the line “pots”, for example, is transformed as follows:

p   o   t   s
p   o   t   s   newline
o   t   s   newline   p
t   s   newline   o   p
s   newline   t   o   p
newline   s   t   o   p
s   t   o   p

And so, appropriately, we finish with “stop”.

This might require GNU sed.

-1

You can use sed:

sed '1!G;h;$!d' inputfile > outfile
2
  • Neat trick, but not what the question is asking for (see the sample input / output and the highest voted (and oldest) answer). Sep 27, 2020 at 5:28
  • That reverses the lines in the file like tac, except for being limited in size, not the chars on each line like rev which is what was requested in this question. Sep 27, 2020 at 6:17

You must log in to answer this question.