brucezepplin
brucezepplin

Reputation: 9752

omit commas from echo output in bash

Hi I am reading in a line from a .csv file and using

echo $line

to print the cell contents of that record to the screen, however the commas are also printed i.e.

1,2,3,a,b,c

where I actually want

1 2 3 a b c

checking the echo man page there isn't an option to omit commas, so does anyone have a nifty bash trick to do this?

Upvotes: 0

Views: 368

Answers (3)

antoniochiurla
antoniochiurla

Reputation: 72

If you have to use the field values as separated values, can be useful to use the IFS built-in bash variable. You can set it with "," value in order to specify the field separator for read command used to read from .csv file.

ORIG_IFS="$IFS"
IFS=","
while read f1 f2 f3 f4 f5 f6
do
        echo "Follow fields of record as separated variables"
        echo "f1: $f1"
        echo "f2: $f2"
        echo "f3: $f3"
        echo "f4: $f4"
        echo "f5: $f5"
        echo "f6: $f6"
done < test.csv
IFS="$OLDIFS"

On this way you have one variable for each field of the line/record and you can use it as you prefer.

NOTE: to avoid unexpected behaviour, remember to set the original value to IFS variable

Upvotes: 0

fedorqui
fedorqui

Reputation: 289715

Use bash replacement:

$ echo "${line//,/ }"
1 2 3 a b c

Note the importance of double slash:

$ echo "${line/,/ }"
1 2,3,a,b,c

That is, single one would just replace the first occurrence.


For completeness, check other ways to do it:

$ sed 's/,/ /g' <<< "$line"
1 2 3 a b c

$ tr ',' ' ' <<< "$line"
1 2 3 a b c

$ awk '{gsub(",", " ")}1' <<< "$line"
1 2 3 a b c

Upvotes: 3

user539810
user539810

Reputation:

If you need something more POSIX-compliant due to portability concerns, echo "$line" | tr ',' ' ' works too.

Upvotes: 1

Related Questions