Replace a section of code in .profile with a file using sed or awk

187 Views Asked by At

I am trying to change a .profile (Ubuntu) as follows:

Original .profile file section:

# the default umask is set in /etc/profile; for setting the umask
# for ssh logins, install and configure the libpam-umask package.
#umask 022

# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
        . "$HOME/.bashrc"
    fi
fi

# set PATH so it includes user's private bin if it exists

I want to change the above code to look like this:

# the default umask is set in /etc/profile; for setting the umask
# for ssh logins, install and configure the libpam-umask package.
#umask 022

BASHRC_CONFIG_DIR=/netshare/users/$USER/

if [ -f "$BASHRC_CONFIG_DIR/.bashrc" ]; then
    . "$BASHRC_CONFIG_DIR/.bashrc"
fi



# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$BASHRC_CONFIG_DIR/.bashrc" ]; then
        . "$BASHRC_CONFIG_DIR/.bashrc"
    else
        if [ -f "$HOME/.bashrc" ]; then
            . "$HOME/.bashrc"
        fi
    fi
fi

# set PATH so it includes user's private bin if it exists

I've tried so many iterations of sed to replace the block in the top file with a file that contains the bottom section and am bashing my head against the wall. Does anyone have any sed (or awk) knowledge they can impart on me so that I may achieve this and put an ice pack on my head?

I've tried this:

sed -n \
  -e "1,/umask 022/ p" \
  -e"/set PATH/,$ p" \
  -e "/umask 022/ r profile_insertion" \
  /home/username/.profile.bak

And this:

sed -i 's/(umask 022).*(#set PATH)/\1 profile_insertion \2/g' /home/username/.profile

(profile_insertion contains the text I want to put in place)

1

There are 1 best solutions below

2
Rick M On

If you can recast it as chopping off the top of the file and replacing it, you can use awk (see Remove all lines before a match with sed).

Make sure profileinsertion has everything you'd need from the beginning of the file, and use something like:

cp profileinsertion profile.out; awk '/set PATH so it/{p++;if(p==1){next}}p' /home/username/.profile >> profile.out

...changing your filenames as needed.