Reputation: 136
I have file which have multiple rows of columns which need to be handled as per requirement. I found a script that does this with variables, but I don't want do this with variables as this makes my code more complex
file:
Id,Name,class,Section
1,Dileep,MBA,B
2,Pavan,tenth,C
3,Girish,graduate,D
My output file should be like this -
file:
Id,Name,Class,Section
1,Dileep,MBA,B
2,Pavan,MCA,C
3,Girish,MBA,D
I have used sed command to do this and below is the script I created for this.
#! /bin/sh
file=/tmp/dileep/details.txt
cat $file | sed '/Id,Name,/s/class/**C**lass/g' | tee -a $file
cat $file | sed '/2,Pavan,/s/tenth/**MCA**/g' | tee -a $file
cat $file | sed '/3,Girish,/s/graduate/**MBA**/g' | tee -a $file
I am able to get the first line changed the one with header, but not the actual data, this is going to be hard-coded data and I can make this change.
Can you please let me know what I am doing wrong and how I can get this corrected.
Upvotes: 0
Views: 328
Reputation: 19982
You can use sed in different ways. I will first fix your script
file=/tmp/dileep/details.txt
output=/tmp/dileep/details.out
# Off-topic: cat $file | sed '...' can be replaced by sed '...' $file
cat $file | sed '/Id,Name,/s/class/**C**lass/g' |
sed '/2,Pavan,/s/tenth/**MCA**/g' |
sed '/3,Girish,/s/graduate/**MBA**/g' | tee -a ${output}
With sed you can use the option -e
:
file=/tmp/dileep/details.txt
output=/tmp/dileep/details.out
# No spaces after the last '\' of the line!
cat $file | sed -e '/Id,Name,/s/class/**C**lass/g' \
-e '/2,Pavan,/s/tenth/**MCA**/g' \
-e '/3,Girish,/s/graduate/**MBA**/g' | tee -a ${output}
Or you can use 1 long command (looks terrible):
cat $file | sed -e \
'/Id,Name,/s/class/**C**lass/g;/2,Pavan,/s/tenth/**MCA**/g;/3,Girish,/s/graduate/**MBA**/g' | tee -a ${output}
What you need here is a commandfile:
cat /tmp/dileep/commands.sed
/Id,Name,/s/class/**C**lass/g
/2,Pavan,/s/tenth/**MCA**/g
/3,Girish,/s/graduate/**MBA**/g
And use
cat $file | sed -f /tmp/dileep/commands.sed | tee -a ${output}
or better, avoiding the cat
sed -f /tmp/dileep/commands.sed ${file} | tee -a ${output}
Upvotes: 0
Reputation: 157947
First(!)
You can't use tee like this. As soon as the input file is larger than the buffer size used by tee you will loose your input file.
About the topic, do you mean something like this?
I would use awk
:
sanitize.awk:
BEGIN {
FS=OFS=","
}
$3=="class" {
$3="Class"
}
$3=="tenth"{
$3="MCA"
}
$3=="graduate" {
$3="MBA"
}
{
print
}
Run it like:
awk -f sanitize.awk input.file > output.file
mv output.file > input.file
Upvotes: 1