Question

I have a file with lines of a set format, using delimiters. I want to identify all the lines with the string "password" in the 3rd field and edit them out. As in, put a "# " at the beginning of them. I would also like to remove the existing value for the 4th field. I can't quite work out how to do this. It looks like it should be able to be done in two steps but I cannot work them out. I am using unix shell, so SED, AWK etc. Sample lines of the file are:

database2|~|t1||~|${topuser.username}|~|topuser
database2|~|t1||~|${topuser.password}|~|H4rdt0Gu3ss
database2|~|t1||~|${loguser.username}|~|LOG
database2|~|t1||~|${loguser.password}|~|Ih4v3n01d34y0utry
# database2|~|t1||~|${open.var1}|~|connect
database2|~|t1||~|${tablespace}|~|gis_tbs1

Some may be edited out already and the delimeter is "|~|". Any help please.

Was it helpful?

Solution

Here is a Perl script to achieve your goal:

#!/usr/bin/perl

use warnings;
use strict;

while (<DATA>) {
    chomp;
    my @fields = split /\|~\|/;
    if ($fields[2] =~ /password/) {
        $fields[0] = "# $fields[0]";
        $fields[3] = '';
    }
    print join("|~|", @fields), "\n";
}

__DATA__
database2|~|t1||~|${topuser.username}|~|topuser
database2|~|t1||~|${topuser.password}|~|H4rdt0Gu3ss
database2|~|t1||~|${loguser.username}|~|LOG
database2|~|t1||~|${loguser.password}|~|Ih4v3n01d34y0utry
# database2|~|t1||~|${open.var1}|~|connect
# database2|~|t1||~|${tablespace}|~|gis_tbs1

Here is the one-liner version:

perl -F'/\|~\|/' -ane '$"="|~|"; if ($F[2] =~ /password/) { $F[0]="# $F[0]"; $F[3] = "\n"; } print "@F";' datafile

OTHER TIPS

If I understood your question correctly, then the following should work:

$ awk 'BEGIN{FS=OFS="\|"}$6~/password/{$6="# "$6;$NF=""}1' file
database2|~|t1||~|${topuser.username}|~|topuser
database2|~|t1||~|# ${topuser.password}|~|
database2|~|t1||~|${loguser.username}|~|LOG
database2|~|t1||~|# ${loguser.password}|~|
# database2|~|t1||~|${open.var1}|~|connect
database2|~|t1||~|${tablespace}|~|gis_tbs1

If you mean edit them out by putting # at the start of the line, then you can do:

$ awk 'BEGIN{FS=OFS="\|"}$6~/password/{$NF="";$0="# "$0}1' file
database2|~|t1||~|${topuser.username}|~|topuser
# database2|~|t1||~|${topuser.password}|~|
database2|~|t1||~|${loguser.username}|~|LOG
# database2|~|t1||~|${loguser.password}|~|
# database2|~|t1||~|${open.var1}|~|connect
database2|~|t1||~|${tablespace}|~|gis_tbs1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top