[bash] - Replace blank and string in csv file

Hi all,
i have a .csv file with only two columns, like:

Login;Status
Luca;S
Marco;
Stefano;
Elettra;S
Laura;
...

I need to replace the blank space on Status column whit Enabled end, on the same column, S whit Disabled, like:

Login;Status
Luca;Disabled
Marco;Enabled
Stefano;Enabled
Elettra;Disabled
Laura;Enabled
...

I try with awk and sed, many errors results :mad: i was not familiar with bash... so i hope in your help.
Thank's all.

awk -F';' 'FNR>1 {$2=($2)?"Disabled":"Enabled"}1' OFS=';' myFile
2 Likes

Hello kamose,

If you have only 2 fields as shown in your sample Input_file then following may help you too.

awk -F";" '{printf("%s;%s\n",$1,($2==""?"Enabled":((NR==1)?$2:"Disabled")))}'  Input_file

Thanks,
R. Singh

1 Like

Another variation:

awk '$2=="S"{$2="Disabled"} $2==""{$2="Enabled"}1' FS=\; OFS=\; file
1 Like

bash

while IFS=";" read f1 f2 
do 
[[ $f2 == "S" ]] && echo "$f1;Disabled" || { echo "$f1;Enabled" ;}
done < file
1 Like

Hi looney,
Note that the above code changes the first line of input:

Login;Status

to:

Login;Enabled

but the desired output showed that that line was not supposed to be changed.

To meet the stated requirements just using built-ins in most standard shells, you would need something more like:

while IFS=';' read -r f1 f2
do	[ "$f2" = "S" ] && f2=Disabled
	[ -z "$f2" ] && f2=Enabled
	printf '%s;%s\n' "$f1" "$f2"
done < file.csv

or:

while IFS=';' read -r f1 f2
do	[ "$f2" = "S" ] && f2=Disabled || { [ -z "$f2" ] && f2=Enabled; }
	printf '%s;%s\n' "$f1" "$f2"
done < file.csv
2 Likes

Are all good solutions, I will keep good for many occasions. I have to decide whether to use awk or while. Maybe I will use awk because it's faster in terms of performance (for me), especially on very large file (over 5k lines).

Thanks to all for feedback.

---------- Post updated at 05:53 AM ---------- Previous update was at 04:20 AM ----------

Sorry guys,
but if in file have lines whit only ";" like:

Login;Status
;
;
Luca;Disabled 
Marco;Enabled 
Stefano;Enabled
;
Elettra;Disabled 
Laura;Enabled
;
;
...

how can I remove those lines?
I can not interpret the special character ";" to make awk and sed. Do you have idea how to do?

Thanks.

Modified vgresh99 script

 awk -F';' ' /^;/ {next } FNR>1 { $2=($2) ? "Disabled":"Enabled"}1' OFS=';' file
1 Like

I'm sorry,
the file, before your suggestions is:

Login;Status
;
Luca;S 
Marco;
;
Stefano; 
Elettra;S 
;
Laura;
;
...

I need to delete line whit only ";" char.

Thanks.

Which it does for me:

awk -F';' ' /^;/ {next } FNR>1 { $2=($2) ? "Disabled":"Enabled"}1' OFS=';' file
Login;Status
Luca;Disabled
Marco;Enabled
Stefano;Disabled
Elettra;Disabled
Laura;Enabled

What exactly is your problem?

1 Like

It's perfect!!
Thanks.