0

Let's say I have a list of keys and values in a file as follows:

name=james
age=20
city=

How can I check this list for keys without values (i.e "city") and if there is nothing after the '=' sign, add a hash to the start of the line?

name=james
age=20
#city=
x3nr0s
  • 1,946
  • 4
  • 26
  • 46

5 Answers5

2

You can use the following command:

sed 's/^[^=]\{1,\}=[[:space:]]*$/#&/' file

Explanation:

The s command means substitute and works like this:

s/search/replace/[optional options]

The patterns above are working as follows:

search

^            Begin of line
[^=]\{1,\}   1 or more non = characters
=            The =
[[:space:]]* Optional space before the end of the line
$            The end of the line

replacement

#            The #
&            The match from the above search

If you want to change the file in place, please check: sed in-place flag that works both on Mac (BSD) and Linux

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • 1
    can also use `sed '/=[[:space:]]*$/ s/^/#/'` and mention about `-i` option for inplace editing – Sundeep Oct 24 '17 at 09:45
  • 1
    @Sundeep Good alternative! About `-i`, unless the OP mentions it itself in the question I don't recommend it in order to avoid destroying anybody's data. (You never know who picks this up after a quick Google search without carefully reading the question and answer) – hek2mgl Oct 24 '17 at 09:50
  • 1
    yeah that's good point, I usually link https://stackoverflow.com/questions/5694228/sed-in-place-flag-that-works-both-on-mac-bsd-and-linux – Sundeep Oct 24 '17 at 09:52
1

Using awk

awk -v FS="" '$NF=="="{$0="#"$0}1'

If last field is = then prepend #

OR

awk -v FS="=" '$2==""{$0="#"$0}1'

If second field $2 is null then prepend #

Output:

name=james
age=20
#city=
Rahul Verma
  • 2,946
  • 14
  • 27
0

Using awk:

awk -F'=' '$2==""{sub(/^/,"#")}1' infile

#OR

awk -F'=' '$2==""{print "#" $0;next}1' infile

#OR

awk -F'=' '{print ($2==""?"#":"") $0}' infile

Test Results:

$ cat infile
name=james
age=20
city=

$ awk -F'=' '$2==""{print "#" $0;next}1' infile
name=james
age=20
#city=

$ awk -F'=' '{print ($2==""?"#":"") $0}' infile
name=james
age=20
#city=

$ awk -F'=' '$2==""{sub(/^/,"#")}1' infile
name=james
age=20
#city=
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36
0

You can try that

cat myfile| sed 's/\(.*.=\s*$\)/#\1/'
Valeriane
  • 936
  • 3
  • 16
  • 37
0

One more awk

awk -F= '!$2{$0="#"$0}1' infile
ctac_
  • 2,413
  • 2
  • 7
  • 17
  • That would fail if `$2` evaluates numerically to zero. See [@batMan's answer](https://stackoverflow.com/a/46907103/1745001) for the right approach. – Ed Morton Oct 24 '17 at 23:27