Home > Blockchain >  sed command to comment out text in file
sed command to comment out text in file

Time:03-10

Im trying to comment out lines within a file by a specific word. However there are multiple lines with a similar word.

BBB-m      more info
BBB        more info
BBB-a      more info
BBB-w      more info

Im looking to comment out the line with just 'BBB' Is this possible? Thank you!

sed -i -- 's/BBB/; BBB/g' $file

CodePudding user response:

This should do the trick:

sed -i 's/^[^#]*BBB$/#&/' file

The & character matches the entire portion of the pattern and as @Barmar said in the comments the $ at the end of BBB filters out other lines.

CodePudding user response:

You can use

awk '$1 == "BBB"{$0="; "$0}1' file > tmp && mv tmp file
sed 's/^BBB[[:space:]]/; &/' file > tmp && mv tmp file
sed -E 's/^BBB([[:space:]]|$)/; &/' file > tmp && mv tmp file

The '$1 == "BBB"{$0="; "$0}1' awk command means that if the first field value is equal to BBB, a ; is appended at the line start. Else, the line is output as is.

The 's/^BBB[[:space:]]/; &/' sed command matches a line that starts with BBB and any one whitespace and then is replaced with ;, space and the matched text. The -E POSIX ERE variation with ^BBB([[:space:]]|$) allows matching BBB as a standalone line.

See the online demo:

#!/bin/bash
s='BBB-m      more info
BBB        more info
BBB-a      more info
BBB-w      more info'
awk '$1 == "BBB"{$0="; "$0}1' <<< "$s"
echo "---"
sed 's/^BBB[[:space:]]/; &/' <<< "$s"

Both return

BBB-m      more info
; BBB        more info
BBB-a      more info
BBB-w      more info

CodePudding user response:

Using sed

$ sed '/[[:punct:]]/!{s/BBB/; &/}' input_file
BBB-m      more info
; BBB        more info
BBB-a      more info
BBB-w      more info
  • Related