How to use sed to remove certain text base on regular expression
2013-09
I got a text file with contents like below
2012/03/15 : "Password":"@#4JF9u92r","Name":"John"
I wish to use sed to change the above to
2012/03/15 : "Password":"XXX","Name":"John"
I have tried the following command
cat log.txt | sed 's/\("Password":\"\)\(.*\)\(\",\"Name\":\)/\1XXX/'
But it gives me
2012/03/15 : "Password":"XXX"John"
What did I do wrong?
Thanks!
You should slightly change your sed
command:
sed 's/\("Password":\"\).*\(\",\"Name\":\)/\1XXX\2/'
Below regex is the base one, place necessary escape characters
(\s"Password":")(.*?)(","Name":"(.*?)")
Replace with \1XXX\3
After placing proper escape characters, I think it should be something like this.
cat log.txt | sed '\(s/\"Password\":\"\)\(.*?\)\(\",\"Name\":\"\(.*?\)\"\)/\1XXX\3/'
This might work for you:
echo '2012/03/15 : "Password":"@#4JF9u92r","Name":"John"' |
sed 's/\("Password":"\)[^"]*/\1XXX/'
2012/03/15 : "Password":"XXX","Name":"John"
In solaris, I'd like to copy all files found by the find command to a slightly different path. The following script basically executes cp for each file found by find. For example:
cp ./content/english/activity1_compressed.swf ./content/spanish/activity1_compressed.swf
cp ./content/english/activity2_compressed.swf ./content/spanish/activity2_compressed.swf
...
#!/bin/bash
# Read all file names into an array
FilesArray=($(find "." -name "*_compressed.swf"))
# Get length of an array
FilesIndex=${#FilesArray[@]}
# Copy each file from english to spanish folder
# Ex: cp ./english/activity_compressed.swf ./spanish/activity_compressed.swf
for (( i=0; i<${FilesIndex}; i++ ));
do
source="${FilesArray[$i]}"
# Replace "english" with "spanish" in path
destination="$(echo "${source}" | sed 's/english/spanish/')"
cp "${source}" "${destination}"
done
exit 0;
It seems like a bit much and I wonder how to use sed in-line with the find and cp commands to achieve the same thing. I would have hoped for something like the following, but apparently parentheses aren't acceptable method of changing order of operation:
find . -name *_compressed -exec cp {} (echo '{}' | sed 's/english/spanish/')
There are easier ways, but for portability sake we can use a bit of forking and backticks:
find . -name *_compressed -exec sh -c 'cp {} `echo {} | sed 's/english/spanish/'`' \;
I'd use the backtick: you'll find more upon it here (backtick is at chapter 3.4.5).
Basically when you enclose a command between backticks the command itself will be substituted in his output.