0

I have a file that contains

coffe
milk
water
etc..

I want to comment out one line, e.g., milk using a variable that contains milk or #milk.

I'm trying to use # as switch.

checkval="milk"

When I use

sed 's/^.//' $file

this remove the first character on all lines.

When I use

sed -e "s/$checkval/\#$checkval/g" $file

this works by adding #.

I expect the following output file when the variable contains the value #milk:

coffe
milk
water

The expected output when the variable contains the value milk:

coffe
#milk
water
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
miszczu
  • 39
  • 5

3 Answers3

0

Below script will do the required tasks.

checkval="#milk"
initial="$(echo $checkval | head -c 1)"
if  [ "$initial" = "#" ] 
then
new_checkval="${checkval:1}"
sed -e 's_'$checkval'_'$new_checkval'_g' input.txt
else
sed -e 's_'$checkval'_#&_g' input.txt
fi

If the checkval is milk and the word milk is present in the file then it will be replaced by #milk. Similarly, If the checkval is #milk and the word #milkis present in the file, it will be replaced with milk.

j23
  • 3,139
  • 1
  • 6
  • 13
  • 1
    Of course this script do required task! My mistake in other files. Thanks a lot! – miszczu Aug 14 '19 at 12:58
  • @miszczu you are welcome. I am glad it helped. If it really helped, you may upvote or accept the answer. Thank you. – j23 Aug 14 '19 at 13:06
  • 1
    yes, i know, but unfortunetly i'm fresh user & got message: Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score. – miszczu Aug 16 '19 at 05:22
  • @miszczu Oh i see. Thank you. Maybe, can you accept the answer? – j23 Aug 16 '19 at 08:59
0

You may use an if condition to check if the checkval starts with a # char and implement different logic:

  • If the checkval starts with #, you need to run the sed command using the checkval in the LHS as is and use the ${checkval:1} (checkval without the first character) in the RHS
  • Else, you need to search for checkval and replace it with # and the text found.

Consider using

checkval="milk";
if [[ $checkval != \#* ]]; then
  sed "s/$checkval/#&/" file > newfile
else
  sed "s/$checkval/${checkval:1}/" file > newfile
fi;

See this demo and this demo, too.

NOTE: If your search phrases can contain any chars, consider escaping the patterns appropriately.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Thanks for the quick reply. I try both solution, and both works, but not as expected. I think I mixed up a little bit... My fault, sorry. I have file:

coffe
milk
water

and the checkval contains milk I suppose the output file will have like this:

coffe
#milk
water

In the second case file contains:

coffe
#milk
water

checkval: #milk output file will be:

coffe
milk
water

I trying to deny conditions , but this not work.

miszczu
  • 39
  • 5