I have a test.txt file looking like this :
a,1,A
b,2,B
c,3,C
d,4,D
e,5,E
f,6,F
I want to modify the second field with some condition :
if value is 1 I modify it to 1_PLUS
if value is 4 I modify it to 4_PLUS
if value is 6 I modify it to 6_PLUS
otherwise modify it to an empty field.
The final file will look like this :
a,1_PLUS,A
b,,B
c,,C
d,4_PLUS,D
e,5,E
f,6_PLUS,F
I wrote a bash script test.sh to do the substitution :
ITEM=$1
case $ITEM in
1)
LOC=1_PLUS
;;
4)
LOC=4_PLUS
;;
6)
LOC=6_PLUS
;;
*)
LOC=
;;
esac
echo $LOC
Then I launch the command like this : I give the $2 argument to my test.sh script to do the substitution and modify the $2 in awk with this new value.
cat test.txt | awk -F, '{$2=$(system("bash ./test.sh "$2))}'
The result is :
1_PLUS
4_PLUS
6_PLUS
So I think I'm close to the solution but I don't understand why modifying the second field with $2=(result of my bash script) doesn't work
I need to keep the cat test.txt |
first because in real life I have a longer command...
Thanx for your help
To "modify a column with awk and a bash script":
awk 'BEGIN{FS=OFS=","} {cmd="bash ./test.sh " $2; cmd | getline $2; close(cmd); print}' test.txt
Output:
a,1_PLUS,A b,,B c,,C d,4_PLUS,D e,,E f,6_PLUS,F
If you use system()
its output is printed automatically. That's not what you want here.