Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 163
  • Last Modified:

Column value change script

I would like to create a bash script that can replace the last column value with text.

test data
Rob;Wright;20;PC;2015;Type;2
Rob;Wright;20;PC;2015;Type;4
Rob;Wright;20;PC;2015;Type;5

wanted output
Rob;Wright;20;PC;2015;Type;fire
Rob;Wright;20;PC;2015;Type;water
Rob;Wright;20;PC;2015;Type;earth

I believe I could use awk or sed to this but not sure where to begin. Can you someone point me in the right direction.

 awk '/regexp/{gsub(/foo/, "bar")};{print}' file.txt
0
DOCDGA
Asked:
DOCDGA
  • 2
1 Solution
 
ozoCommented:
awk -F';' 'BEGIN{OFS=FS;e[2]="fire";e[4]="water";e[5]="earth"}{$7=e[$7];print}'
0
 
TintinCommented:
You could use sed, but not as flexible as awk/perl.

sed -e "s/2$/fire/" -e "s/4$/water/" -e "s/5$/earth/  filename

or put all the sed commands into a file, eg:

s/2$/fire/
s/4$/water/
s/5$/earth/

And invoke with

sed -f myfile.sed filename
0
 
DOCDGAAuthor Commented:
Tried this solution
awk -F';' 'BEGIN{OFS=FS;e[2]="fire";e[4]="water";e[5]="earth"}{$7=e[$7];print}' file.txt
Output:
Rob;Wright;20;PC;2015;Type;fire
Rob;Wright;23;PC;2015;Tyep;water
Robi;werwea;43;ibb;3424;tt;earth
;;;;;;
;;;;;;
;;;;;;
Don't know why I'm receiving extra semicolons
0
 
ozoCommented:
Were there extra blank lines in file.txt ?

If not all lines contain 7 fields, you may prefer something like
awk -F';' 'BEGIN{OFS=FS;e[2]="fire";e[4]="water";e[5]="earth"}{$NF=e[$NF]}1' file.txt
or
awk -F';' 'BEGIN{OFS=FS;e[2]="fire";e[4]="water";e[5]="earth"}e[$NF]{$NF=e[$NF]}1' file.txt
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now