Reputation: 135
I am having the text file as below. that file contains some negative data. so I want to replace that data with zero.
1,2,3
4,5,-6
7,-8,9
I have tried with below command.
sed 's/-*/0/g' 1.txt
but am not getting the reqired output. so can any one please help me on this.
Upvotes: 1
Views: 486
Reputation: 37404
awk:
$ awk 'gsub(/-[0-9]+/,0)1' 1.txt
Identical to @redneb's sed solution but in awk. Replace all -
starting number strings ([0-9]+
) with a 0
in record $0 and print it nevertheless (1
in the end).
Upvotes: 1
Reputation: 246774
With awk, you would write
awk -F, -v OFS=, '{for (i=1; i<=NF; i++) if ($i < 0) $i = 0; print}' file
My sed would be
sed -r 's/(^|,)-[^,]+/\10/g' file
Upvotes: 1
Reputation: 2011
You have to better understand regular expression for sed.
The expression -*
in s /-*/0/g
will match zero or more '-' characters. *
in regular expression means zero or more duplicates, not wild character match, .
does all character set match for a single character. See http://www.grymoire.com/Unix/Regular.html
To your question, you have to build a RE to match any negative number (maybe you need also consider float numbers). I would suggest:
-[0-9]*\.?[0-9]+
This is an extended regular expression for sed program, meaning that starts with -
, can with or without pre-dot numbers or dot, and must contain at least one number.
So
sed -r s/-[0-9]*\.?[0-9]+/0/g 1.txt >2.txt
is what you need. -r
option means use extended regular expression.
Some tests:
echo '12, 0.12, -2' | sed -r s/-[0-9]*\.?[0-9]+/0/g
12, 0.12, 0
echo '12, -234, -2' | sed -r s/-[0-9]*\.?[0-9]+/0/g
12, 0, 0
echo '-0.98, 2.34, -2' | sed -r s/-[0-9]*\.?[0-9]+/0/g
0, 2.34, 0
echo '-9.8, 0.34, -2' | sed -r s/-[0-9]*\.?[0-9]+/0/g
0, 0.34, 0
echo '-9.8, 1.34, -2' | sed -r s/-[0-9]*\.?[0-9]+/0/g
0, 1.34, 0
Hope this would be helpful, check tutors on http://www.grymoire.com/Unix/Sed.html.
Thanks
Upvotes: 1
Reputation: 23850
Try this:
sed 's/-[0-9]\+/0/g' 1.txt
The way this works is, sed
will find all sequences of characters that match the pattern -[0-9]\+
and replace them with a 0
. Now, they meaning of the -[0-9]\+
pattern is as follows: it will find a -
character followed by a nonempty sequence of characters (this is the meaning of \+
) that consists entirely of characters in the set between 0
and 9
.
Upvotes: 2