Berchev
Berchev

Reputation: 87

Shell script not working as expected

I have issues with part of my shell script

if [ -e ~/linux/content.txt ]
then
cat ~/linux/content.txt | sed -re 's/<head>//g' > ~/linux/content_temp.txt
rm content.txt
cat ~/linux/content_temp.txt | sed -re 's|</head>||g' > ~/linux/content.txt
rm content_temp.txt
cat ~/linux/content.txt | sed -re 's/<body>//g' > ~/linux/content_temp.txt
rm content.txt
cat ~/linux/content_temp.txt | sed -re 's|</body>||g' > ~/linux/content.txt
rm content_temp.txt
CONTENT=$(grep -v "^[[:blank:]]*#" ~/linux/content.txt)
echo $CONTENT
else
echo "Content file not found"
fi

It just deletes the file and stops... It has to check for the words delete them and then at the end I have to have a clear content.txt file but I don't. Could you let me know why?

Upvotes: 1

Views: 159

Answers (2)

Jacobo de Vera
Jacobo de Vera

Reputation: 1933

You are not making the removal of the files conditional to the success of the previous command.

Perhaps in this case it is worth exploring set -e so that the script stops in the first command that exits with non-zero return code, together perhaps with set -v to show you which commands are being run.

that being said, you can greatly simplify your script if you use sed's in place replacement with the -i flag. It does the replacements in the same input file and then you don't need two files:

if [ -e ~/linux/content.txt ]
then
  sed -ri 's/<head>//g' ~/linux/content.txt
  sed -ri 's|</head>||g' ~/linux/content.txt
  sed -ri 's/<body>//g' ~/linux/content.txt
  sed -ri 's|</body>||g' ~/linux/content.txt
  CONTENT=$(grep -v "^[[:blank:]]*#" ~/linux/content.txt)
  echo $CONTENT
else
  echo "Content file not found"
fi

Edit:

Additionally, and since you are making all modifications to the same file, you can do them all in one single sed call, as suggested in the other answer, either by using -e or simply by putting one sed command in its own line:

file=~/linux/content.txt
if [ -e "$file" ]
then
  sed -r -i.bak -e 's/<head>//g
s|</head>||g
s/<body>//g
s|</body>||g
/^\s*$/d' "$file"
  cat "$file"
fi

Please note that sed not only can do text replacement, but it can also, among other things, remove lines that match certain pattern, like empty lines with: /^\s*$/d, so you'd no longer need the grep invocation you had.

Also note the -i.bak in the sed line. The -i flag of sed can take a parameter that will be used as a suffix on the original file name to preserve a copy of the original, so when you run this, you'll be left with one file called ~/linux/content.txt.bak with the original contents. This, of course, only makes sense if you use only one sed command, otherwise your backup file will get overwriten in each call.

Upvotes: 1

Pavel
Pavel

Reputation: 7552

you can do also everything in one line:

sed -ri -e 's/<\/?head>//g' -e 's/<\/?body>//g' content.txt
grep ...

Upvotes: 2

Related Questions