It took me a long long time to change the IFS (Internal Field Separator) in a bash shell. Which by the way is set as default to whitespace, tab, linefeed and carriage return.
If you want to change it in the shell you have to enter: IFS="whatever you want"
You can view the same using : echo $IFS | cat -vte
My problem was to rename files with spaces in them. As for loop was breaking each file name at space.
So I had to do the following:
# Before you modify your IFS please please please make sure you save your old IFS just in case things do not go as expected. Remember Murphy's Laws are omnipresent!
#IFS=:Space:Tab:Line Feed:Carriage Return:
IFS=$'\x20'$'\x09'$'\x0A'$'\x0D'
Then rename each file.
for f in `ls *.txt`; do
echo $f
# change each file extension from .txt to .csv
mv $f `basename $f .txt`.csv
#Additionally if you want to remove the whitespace too then the following line replaces it with underscore!
# mv $f `basename $f .txt|sed 's/ /_/g'`.csv
done
And done in seconds..
sigh (of relief and happiness)!!!
Happy bashing! :)
Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts
Monday, February 23, 2009
Saturday, October 13, 2007
Redirection In *nix
After having gone through "search implement and forget" cycle of redirection in *nix environment. I thought it will be best in my interest to just make a small note on it on my blog. So that I have it at an easy to remember and accessible place.
To redirect both stderr and stdout streams on a bash shell you need to do:
command args >& logFile
To redirect only the stderr you should do only:
command args 2> logFile
NOTE: If you invoke a subshell like:
sh shell_script
Then you should encapsulate the command within apostrophe(') to prevent the parent shell interpreting and converting the stderr stream to an integer. This is because, if you invoke your script in the aforementioned way, then the parent shell invokes a child shell and tries to do substitutions where ever possible.
I should be explaining this more in detail in future, maybe :)
To redirect both stderr and stdout streams on a bash shell you need to do:
command args >& logFile
To redirect only the stderr you should do only:
command args 2> logFile
NOTE: If you invoke a subshell like:
sh shell_script
Then you should encapsulate the command within apostrophe(') to prevent the parent shell interpreting and converting the stderr stream to an integer. This is because, if you invoke your script in the aforementioned way, then the parent shell invokes a child shell and tries to do substitutions where ever possible.
I should be explaining this more in detail in future, maybe :)
Labels:
bash,
Linux shell,
redirection
Subscribe to:
Posts (Atom)