I want to substitute &|$ with comma in csv file. How can I do it using bash?
CodePudding user response:
I would use perl for this.
perl -pe 's/\|/,/g' file.txt
That's substitute
\|
Pipe (or $ or &) with a backslash to 'protect' it
,
Replace with comma
g
Globally
CodePudding user response:
In pure bash, no tools not built into the shell itself:
#!/usr/bin/env bash
# ^^^^ - run this with _bash_, not sh
while IFS= read -r line; do
printf '%s\n' "${line//[&$|]/,}"
done <in.csv >out.csv
CodePudding user response:
As pointed out, in pure bash
$: x='&|$'
$: echo ${x//[&|$]/,}
,,,
If you want the whole string converted to a single comma,
$: echo ${x//'&|$'/,}
,
If you want any consecutive set of those characters converted to a single comma...
$: shopt -s extglob; echo ${x// ([&|$])/,}
,
Processing a whole file can use a read loop to parse each line, or something more all-at-once, with some caveats - the read loop is generally safer. Be careful with your quoting either way.
$: shopt -s extglob; x="$(<x)"; printf "%s\n" "$x" "***" "${x//'&|$'/,}"
&|$
foo
&|$
bar
&|$
baz
&|$
***
,
foo
,
bar
,
baz
,
But generally, I'd use something like sed
$: sed -E 's/\&\|\$/,/g' x # every occurrence of this exact sequence
,
foo
,
bar
,
baz
,
or awk
$: awk '{gsub("[&|$] ",",")}1' x # any consecutive combination of these characters
,
foo
,
bar
,
baz
,