I would like to replace * with a number.
ifile.txt 2 3 4 ***** 3 3 4 ***** 1 2 1 ***** desire output
ofile.txt 2 3 4 999 3 3 4 999 1 2 1 999 I was trying with
sed -i 's/*****/999/g' ifile.txt But not working.
You need to escape the special character * using \, i.e.:
sed -i 's/\*+/999/g' ifile.txt Will match 1 or more * (\*+) and replace it with 999
\\ inside single quoted (') parameter?+ with \+ or use sed -r. Not sure about BSD sed.Try
sed -i 's/\*\*\*\*\*/999/g' ifile.txt Because * is one of the most basic special characters in RE. See POSIX BRE and directly from specification see QUOTED_CHAR.
* inside sed patterns is and how it can be escaped with a backslash.* is a special character (one of the most basic ones). For future reading POSIX BRE and directly from specification see QUOTED_CHAR.sed, don't you think you should start by learning how regular expressions work? There's a tutorial at www.regular-expression.info.Without -r could not work
If you need to replace exactly 5 * with 999.You can also use this:
sed -r 's/\*+/999/g' ifile.txt In regular expressions + is used to match one or more consecutive repetition of
sed -r 's/\*{5}/999/g' ifile.txt In regular expressions {n} is used to match exactly n consecutive repetition of
sed -r 's/\*{2,5}/999/g' ifile.txt In regular expressions {n,m} is used to match minimum n and maximum m consecutive repetition of
To be sure that your expression work as your expectation use -r, because sed standard expression (a reduced rule set) vary from unix/linux distribution, so use -r to be sure that all the regular expression rules will be applied (without the need of escaping +,{,},(,) special chars).
+ is not "any" number of repetitions, it's "one or more". * is "any number", including zero. And -r is not required, it just allows you to skip escaping some special characters: sed 's/\(x.\+\{2,3\}\)/y/' is equivalent to sed -r 's/(x.+{2,3})/y/'.$ cat t.awk function sgsub(r, t, s, m, i, prefix, ans) { # substitutes `t' for # all occurence of the # string `r' in the # string `s' m = length(t) while (i = index(s, r)) { prefix = substr(s, 1 , i-1) s = substr(s, i + m ) ans = ans prefix t } ans = ans s return ans } BEGIN { old = "*****" new = "99999" } { print sgsub(old, new, $0) } Usage:
echo '2 3 4 *****' | awk -f t.awk awk -f t.awk infile.txt You can do this with gawk. The following code replaces the asterisks in fourth column with three nines.
gawk '{gsub(/*****/,"999",$4)}1' file 2 3 4 999 3 3 4 999 1 2 1 999