Tuesday, March 2, 2010

Bash Scripting - Adding pipe "|" to each line of text file

Here is a simple script which will add a pipe symbol '|' to the start and end of every line in a text file.

Well do not ask why I need to do this, it was needed for some nasty text files which we have to deal with in our day to day works.

Someone will argue why the hell we need a script for this simple task when we can do the same with 'vi', well I must say chill mate...yes there are more then one way to do the work done, and using the script way you don't have to open a file or what if you have to work with more then one txt file? its easy to run a script "add_pipe" and sit back instead of vi file1;vi file2. :)

Script can be easily modified to accept the "SOURCEDIR" from command line or adding any other symbol, currently I put all such text files in /tmp/manual before running the script.

The Script:

#!/bin/sh
# Purpose: To add pipe '|' to begin and end of line in a txt file.
# Date: 2010-02-25
# add_pipes

# Directory to where files need to process for adding pipe
SOURCEDIR="/tmp/manual"

# Change to source directory
if [ -d "$SOURCEDIR" ];then
 cd "$SOURCEDIR"
else
 exit 1
fi

# First convert the files to Unix (if imported from M$ files carries the carrige return
CR='\015'  # Carriage return.
           # 015 is octal ASCII code for CR.
           # Lines in a DOS text file end in CR-LF.
           # Lines in a UNIX text file end in LF only.

for file in $(ls)
do
 if [ ! -d "$file" ];then
  tr -d $CR < $file >newname
  mv newname $file
 fi
done

# Finally add pipe by loop through files
for file in $(ls)
do
 if [ ! -d "$file" ];then
  #sed -e 's/^/|/g' -e 's/\r$/|/g' < $file >newname
  sed -e 's/^/|/g' -e 's/$/|/g' < $file >newname
  mv newname $file
 fi
done
# End

3 comments: