Reputation: 28339
I want to extract lines that don't contain #
and delete "
, ;
in the output.
My input FILE looks like this:
# ;string"1"
# string"2";
string"3";
Can use grep
and tr
to get wanted output:
grep -v '#' FILE | tr -d ';"'
string3
However I want to use awk
.
I can extract invert match awk '!/#/' FILE
, but how can I use sub
to delete "
, ;
in the same awk
command?
Upvotes: 7
Views: 12206
Reputation: 881563
You can use gsub
for global substitution:
awk '!/#/{gsub(/[";]/,"",$0);print}'
The following transcript shows this in action, it delivers the same results as your grep/tr
pipeline:
pax> echo '# ;string"1"
# string"2";
string"3";' | awk '!/#/{gsub(/[";]/,"",$0);print}{}'
string3
Note that the final {}
may not be necessary in some implementations of awk
but it's there to stop output of non-matching lines in those implementations (usually older ones) that do it automatically for lines matching none of the rules.
Upvotes: 5
Reputation: 75488
Use gsub
instead which would replace all matches not just one:
awk '/#/{next}{gsub(/[";]/,"")}1' file
Output:
string3
gsub
makes it process $0
by default./#/{next}
makes it skip lines containing #
1
makes it print $0
Upvotes: 3
Reputation: 785196
If you want to give sed
a chance:
sed -n '/^[^#]/s/[";]//gp' file
string3
Upvotes: 2
Reputation: 41456
Another awk
version
awk -F"[\";]" '{$1=$1} !/^#/' OFS= file
string3
awk '{gsub(/[";]/,x)} !/^#/' file
string3
The x
represents nothing. Could also have used ""
, but saves one characters :)
Upvotes: 2