Posts Tagged: bash


7
Dec 06

Reverse the order of lines

EDIT: There is tac.

I had to reverse the order of lines in very long files once, and not being able to think of an efficient way to do that with bash, I asked Paolo if there was a reversing tool that I did not know about. He told me that he did not know of any, but that he knew a very bash way to do the task. Intrigued, I started thinking.

In the end, I was able to think up of three (3) approaches to the problem. This solution:

cat -n $FILE | sort -rn | cut -f2

however, feels very childlike, so it is my favorite. I do not know how exactly sort does its sorting, though, so I do not know how efficient this solution really is.


24
Nov 06

Studying?

touch -a philo-readings
while read clause
do
    # Do nothing ... successfully.
    true
done < philo-readings

13
Feb 06

Tidying up my BASh customizations

My ~/.bash_profile file was already getting too cluttered with environment customizations that I decided to tidy things up a bit. I moved all the lines I had previously added to that file to ~/.bash_miscellaneous, and added the following lines at the end of the former file:

if [ -e ~/.bash_miscellaneous ] && [ -f ~/.bash_miscellaneous ]
then
    . ~/.bash_miscellaneous
fi

I am more at peace now.


15
Dec 05

for loops and whitespaces

It appears that for loops in BASh treat not just newlines, but also tabs and spaces as separators in a list. This may be useful in a lot of situations, but when needing to process each line, possibly with whitespaces, from input individually, things get a little messy. Given a file test that contains the following backslash-escaped text, for example:

This is\tconfused behavior.\nWhat is up?

the following code:

for line in `cat test`
do
    echo $line
done

gives:

This
is
confused
behavior.
What
is
up?

After reading documentation and other references, I decided to just settle for while loops when faced with the problem again. The following code:

while read line
do
    echo $line
done < test

properly prints out each line in the file test.

This may be asking too much, and I may be seeing this from a very shallow perspective, but I found myself wishing lists could take arguments too. I think one can actually make a script for this.