SED: Place char at starting and replace selected line


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting SED: Place char at starting and replace selected line
# 1  
Old 04-20-2009
Bug SED: Place char at starting and replace selected line

Hello Experts,

I am working on a small file editing script. Since all experts here are very generous to give me the complete code, I would take up the problem in steps so that I ensure my opportunity to learn.

AIM: The script has some commented and some uncommented lines. I need to :
  1. Comment and uncomment lines as per requirement
  2. Change some lines, again as per requirement
  3. The requirement is specified by the command line arg
Here is what I have thought of:
  1. Place # in front of all uncommented lines.
  2. edit the required line
Suppose my file f.txt is:
Code:
#qwertyu
asdfgh
#zxcvbnm
qwertyuiop

The desired o/p is:
Code:
#qwertyu
#asdfgh
#zxcvbnm
#qwertyuiop

What I tried:
Code:
sed 's/^/#/g' f.txt > result.txt             # first command
sed 's/^[^#]/#/g' f.txt > result.txt      # second command

The problem is:
First command places a # in front of each line, not that it's a problem as I am simply concerned with commenting the lines, but I want to know if what I am trying is possible.
Second command replaces the first character too Smilie.

Please provide me some ideas to approach this problem.

If you think I am headed in the wrong direction, pls correct me and advise some other way to accomplish my task.

Kindly avoid direct code solutions, hints are most welcome.

Thank You.

Regards,
HKansal

Last edited by hkansal; 04-21-2009 at 10:44 AM.. Reason: corrected typo
# 2  
Old 04-20-2009
step 1 done

Hello again,

This solves my first problem: Smilie
Code:
sed 's/^[^#]/#&/g' f.txt > result.txt

Now I am looking to edit a particular line, ll try it after having something to eat... hungry.

I'll get back to you all if have troubles Smilie

Still if you have any better approach to the problem, pls share.

Regards,
HKansal
# 3  
Old 06-11-2009
MySQL Final Script

Hello Experts,

Here is the final script:

Code:
#############################################################
## 
## Shell    : hDeploy
##
## Author     : Himanshu Kansal
##
## Date        : April 23, 2009 (Thursday)
##
## Description    : The shell takes in the Properties File Name,
##          Environment Name and Application Names as input
##          and edits the OM.props file accordingly.
##
## Version     : v0.01a
##
## Enhancements : It should be enhanced to take care of
##          1. Deployment steps.
##          2. New Initiatives/Applications.
## 
## Usage    : sh hDeploy <propsFile> <env> <app_1> [<app_2> ...]
##
## Notes     : 1. All parameters should be correct for desired o/p
##          2. If a parameter value is incorrect, run again 
##             with correct values
## Dependencies : apps.txt - Contains mapping of application names with numbers.
##
## TO-DO      : 1. Call cleanUp() wherever necessary. (Priority : low, Severity : Not Severe)
##
#############################################################

#!/bin/sh

################################################
##
## Function     : getEnvPath
## Objective    : Check if input env is valid
## Description     : Initialise path value of EAR if valid,
##          else exit with error message
## Date     : April 23, 2009
## Author    : Himanshu Kansal
## 
################################################
getEnvPath(){
    
    # Variables used :-
    # ==============
    # var : The environment argument passed

    var=$1    
    
    case "$var" in
        [CS]IT[1-4])            
            ;;
        PSDEV | PSSIT)            
            ;;
        *)            
            return 1
            ;;
    esac
    
    echo "/tmp/OM/OM_"${env}
}

################################################
##
## Function     : getAppNum
## Objective    : Get the number of application
## Description     : Return App Number according to App          
## Date     : April 28, 2009
## Author    : Himanshu Kansal
## 
################################################
getAppNum(){
    
    # Variables used :-
    # ==============
    # appName : Name of the application
    
    appName=$1    
    
    ## Check App Name and return 1 if NOT ok    
    findApp=`grep '^'"$appName"'=' ${appsFile}`
    if [ ${#findApp} -eq 0 ];then
        ## App Name not found, return 1
        return 1
    fi

    grep "${appName}" ${appsFile} | head -1 | awk -F"=" '{print $2}'
}

################################################
##
## Function     : giveUsage
## Objective    : Show the Shell Usage to user
## Description     : Prints the valid usage syntax
## Date     : May 19, 2009
## Author    : Himanshu Kansal
## 
################################################
giveUsage(){

    echo "USAGE :"
    echo "\tsh hDeploy <propsFile> <env> <app_1> [<app_2> ...]"
    
}

################################################
##
## Function     : uncomment
## Objective    : Un-comment a particular line
## Description     : Un-comments the input line and saves the changes source
##           file to destination file.
## Date         : June 1, 2009
## Author    : Himanshu Kansal
## 
################################################
uncomment(){

    # Variables used :-
    # ==============
    # lineToEdit    : The line ofthe file to edit
    # srcFile        : Source file to edit
    
    lineToEdit=$1
    srcFile=$2

    awk "/^#${lineToEdit}/{sub(/^#/,\"\")} 1" ${srcFile}

}

################################################
##
## Function     : cleanUp
## Objective    : Removes all the temporary files created
## Date         : June 1, 2009
## Author    : Himanshu Kansal
## 
################################################
cleanUp(){
    
    rm -rf htmp.props htmp2.props
        
}

# Variables used :-
# ==============
# env           : Environment for deployment
# envPath     : Path of the ear file for this environment
# propsFile     : The properties file to edit
# appsFile     : The file with number of apps


## Command-line Arguments:
## - $1     : propsFile
## - $2     : Environment
## - $3,... : Applications (Space separated values)

propsFile=$1    
env=$2
appsFile="apps.txt"

## Check if Props file is mentioned
if [ "${#1}" = "0" -o ! -s ${propsFile} ];then
    
    ## No Props File Name specified
    echo "\nA props file was not provided or File \"${propsFile}\" not found."
    giveUsage

    ## Safely exit with non-zero code
    exit 1
    
fi

## Get path for this environment
envPath=`getEnvPath "${env}"`

## Exit with message if environment is invalid
if [ $? -ne 0 ];then

    echo "\nInvalid Env \"${env}\": Exiting"
    giveUsage
    
    ## Safely exit with non-zero code
    exit 1    
    
fi 


echo "Environment Path : ${envPath}"


## Forget propsFile and env args, move to other args.
## Check if an Application Name(Eg: OMEAR) is provided.
if [ "${#3}" = "0" ];then

    ## No App Name specified
    echo "\nNo Application specified"
    giveUsage
    
    ## Safely exit with non-zero code
    exit 1
    
else
    
    shift 2
    
fi


#echo "Props File : ${propsFile}"
#cat ./${propsFile}


## Comment all lines in the props file
#echo "[[ Commenting all lines]]"

sed "s/^[^#]/#&/g" ${propsFile} > htmp.props

#echo "[[ Commented all lines ]]"
## Now "htmp.props" is the operation file

## Loop through all the applications specified.
## Get the application number for an app
## Edit the required lines for that app
## Move to next app
## The numbers are stored in file "apps.txt" for easy edit/review/update
for app in $*
do
    
    echo "${app}"
    
    ## Get app num
          appNum=`getAppNum "${app}"`
    #echo "[[App Num]] : ${appNum}"
    
    ## Check return value, exit if 1
    if [ $? -ne 0 ];then
        echo "Invalid Application : Skipping"        
        exit
    fi 

    echo "[[App Num]] : ${appNum}"
    
    ## Edit the required lines

    ## Uncomment line for App Name    
    uncomment "Application\.${appNum}\.name" "htmp.props" > htmp2.props

    ## Edit line for App EAR location
          sed "s~#Application\.${appNum}\.earFile=.*~Application\.${appNum}\.earFile=${envPath}/${app}.ear~g" htmp2.props > htmp.props

    ## Uncomment target cluster          
    #awk "/^#Application\.${appNum}\.target/{sub(/^#/,\"\")} 1" htmp.props > htmp2.props
    uncomment "Application\.${appNum}\.target" "htmp.props" > htmp2.props
          
          ## Un-comment 2 more lines for SMG3TestingToolEAR
    if [ ${app} = "SMG3TestingToolEAR" ];then                
        uncomment "ApplicationLibrary\.${appNum}\.appName" "htmp2.props" > htmp.props
        uncomment "ApplicationLibrary\.${appNum}\.libraryName" "htmp.props" > htmp2.props
    fi

    ## Update htmp.props for next application
    cat htmp2.props > htmp.props

done

## Finally, save result to required file
mv htmp2.props ${propsFile}
echo "File ${propsFile} edited."

cleanUp
exit 0

#####################################################
##            End Of File - hDeploy       ##
#####################################################

Please feel free to review and post comments.

Thank You.

Regards,
HKansal
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Advanced & Expert Users

Replace \n char true line Separator

Unix File is pipe delimited with 17 fields. We may get extra pipes in data also. We may get \n char (1 or more \n in one field or multi fileds) in data in any field. Need to replace \n true ( line separator) with 'space and bell char space' chars (' \a ') Not data \n. Input:... (1 Reply)
Discussion started by: rajeshkumare
1 Replies

2. Shell Programming and Scripting

Match a char with duplicates in a line and replace one of them

Hi, i have a huge file that need to check for a pattern that occur more than once in a line like below:- #lkk>cd-m>A0DV0>192.134.1.1 blablabladsdjsk jshdfskfslfs #lqk>cd-m>A1SV0>192.14.11.1 blalalbnalablab balablablajakjakjakja #pldqw>sf-w>PH67FR>168.55.1.1 balablabala... (5 Replies)
Discussion started by: redse171
5 Replies

3. Shell Programming and Scripting

Find and replace in starting of line using sed

Hi, My requirement is, to find the word "data" and replace the starting of each line with # using sed. /dev/datavg/xxx /xxx ext3 defaults 1 2 /dev/datavg/yyy /yyy ext3 defaults 1 2 result to be #/dev/datavg/xxx /xxx ... (1 Reply)
Discussion started by: ksgnathan
1 Replies

4. Shell Programming and Scripting

sed to delete selected line from file

Ultimate goal is to delete lines from before and after a block of lines in a given file. First attempt was something like this: sed -e '1,/STARTUP/ d' inputfile.txt > outputfile.txt but that deleted everything down to and including the line with STARTUP. I need to delete everything before... (6 Replies)
Discussion started by: edstevens
6 Replies

5. Shell Programming and Scripting

replace line starting with not a number

Dear users, I have a file like this: geometry,geometry_vertex_count,Id,strnum,platecode,datatype,dtnum,refnum,appearance,disappeara,color,geogdesc,datatype_ft_style,import_notes "<LineString><coordinates>-130.6539,51.5103,0 -130.7708,51.6287,0 -130.8356,51.6832,0 -130.9211,51.7772,0... (5 Replies)
Discussion started by: Gery
5 Replies

6. UNIX for Dummies Questions & Answers

UNIX BASH replace char with dash w/o SED

I am trying to create a script in UNIX BASH where I can change the string to dashes. This is part of a "hangman" game (not a homework assignment). Once the dashes are in place, I then need to add the letter to the new string (of dashes) based on where the letter is located. (ie The word is 'String'... (11 Replies)
Discussion started by: needsomehelp
11 Replies

7. Shell Programming and Scripting

Place digit in front of the line searching pattern using sed command

hi All, i want to add the single digit front of the line in the report file and string compare with pattern file. patter file: pattern1.txt pattern num like 4 love 3 john 2 report file: report.txt i like very much but john is good boy i will love u so after execute... (9 Replies)
Discussion started by: krbala1985
9 Replies

8. Shell Programming and Scripting

Delete a line between selected lines using sed or any other command

I want to delete a line between selected lines using sed: e.g. : Between "bus" to "pins", delete lines conaining "signal" word. Input : bus direction signal new signal old pins signal ok end Desired Output: bus direction pins signal end (4 Replies)
Discussion started by: nehashine
4 Replies

9. Shell Programming and Scripting

In vi editor I want to replace next line char by space

in vi editor I want to replace next line char by space help me eg: input: 123 123 123 output: 123 123 123 (5 Replies)
Discussion started by: RahulJoshi
5 Replies

10. Shell Programming and Scripting

Need to print only selected char in a string..?

Hi, I want to print particular chars in a string. for example ie., consider " dear,. roopa$#09%~`';']" as the example string. Here, I want to print only alphanumeric chars.. suppose , if i want only alphanumeric... value would be "dear roopa09" suppose , if i want some spl char(,) with... (2 Replies)
Discussion started by: balan_mca
2 Replies
Login or Register to Ask a Question