Problem with replace command
Question
I have some problem with replace command.
Input file i have this
{a[$1]=a[$1]FS$2}END{for(i in a) print i,a[i]}
I want to replace with single quotes
'{a[$1]=a[$1]FS$2}END{for(i in a) print i,a[i]}'
Using the below mentioned command
find input.txt -exec sed 's/{a[$1]=a[$1]FS$2}END{for(i in a) print i,a[i]}/'{a[$1]=a[$1]FS$2}END{for(i in a) print i,a[i]}'/g' {} \;
I am getting error like this
bash: syntax error near unexpected token `('
Solution 4
Finally i found simple way to do this.
cat input.txt sed "s/{a[$1]=a[$1]FS$2}END{for(i in a) print i,a[i]}/'{a[$1]=a[$1]FS$2}END{for(i in a) print i,a[i]}'/g"
I hope i will helpful
OTHER TIPS
First, you cannot insert easily a literal single quote in an argument that is delimited with single quotes.
You have to replace your '
's with '"'"'
or '\''
.
As a hint to guess this problem, here, the complaint comes from the shell, which means that even your command-line is malformed.
Second, you should be aware that dollar and parentheses are special characters in sed regular expressions. You will probably have to escape them. Read man sed
for more details on this.
Third, I am not sure whether find input.txt
will work. I guess you meant find . -type f -name input.txt
?
It's because the naked '
in your replacement string is actually terminating the sed
command, meaning the shell is trying to process the line. This actually became immediately obvious when Benoit's edit caused your question to syntax-colour correctly. You can see the second '
on the line (the first character of the substitution text) changed the colour from red to black due to the string termination.
In addition, sed
won't like the use of naked []
since they indicate character classes in regular expressions.
You can fix both problems with:
pax> find input.txt -exec sed 's/{a\[$1\]=a\[$1\]FS$2}END{for(i in a) print i,a\[i\]}/\x27{a[$1]=a[$1]FS$2}END{for(i in a) print i,a[i]}\x27/g' {} \;
which outputs:
'{a[$1]=a[$1]FS$2}END{for(i in a) print i,a[i]}'
So basically, escape the square brackets in the search string so they're treated as literals and use \x27
in the replacement string instead of '
.
I find it funny why you should have to do this. You should write the correct code in the first place, since I can see its awk code. Don't tell me you purposely omit the single quote in your input.txt
file when you created it? And its only a single file you are editing. There's no need to use find. (unless you don't know where it is).