Reverse Strings in a Text File
From Notes
Bash
When using Bash, the method that I have come up with is to read the file, line by line, and then prepend each line to a newly created file. This method uses a significant amount of disk I/O and could use some refinement.
An example follows (validation removed for brevity):
#!/bin/bash
# create file to write output to
OUTFILE="${1}_reversed_$$"
STAGING="${1}_staging_$$"
# create outfile and prime with a single line
# to allow sed to work (otherwise there would not be anything to prepend)
echo "test" > ${OUTFILE}
# Switch IFS to newline rather than white space
ifs=${IFS}
IFS='\
'
# open file descriptor to input file
exec 3< $1
START=0
# iterate through file
while read -u 3 LINE
do
# insert line from file before 1st line in outfile
sed '1 i\
'"${LINE}"'' ${OUTFILE} > ${STAGING}
mv ${STAGING} ${OUTFILE}
# remove the last line from the outfile
# cleans up 'test'
if [ ${START} -lt 1 ]
then
sed -i '$d' ${OUTFILE}
START=1
fi
done
# restore white space IFS
IFS=${ifs}
exit 0
