Bash substitution; remove everything after the string
This is probably a very stupid question, but in Bash I want to do the following substitution:
I have in some files the line:
DATE: 12 jan 2009, weather 20°C
and I want to change it to
开发者_运维百科DATE: XXXX
Using sed I guess I had to say "starting after "DATE:", please remove the rest and insert " XXXX".
Is this approach OK and how can I perform it?
Also, I want to learn. If you were in my situation what would you do? Ask here or spend one hour looking at the man page? Where would you start from?
Try:
sed -i 's/^DATE:.*$/DATE: XXXX/g' filename
Answer to your 2nd question depends on how often you need to write such things. If it's a one time thing and time is limited it's better to ask here. If not, it's better to learn how to do it by using an online tutorial.
while read line
do
echo "${line/#DATE*/DATE:xxxxx}"
done < myfile
You can use the following code also
> var="DATE: 12 jan 2009, weather 20ºC"
> echo $var | sed -r 's!^(DATE:).*$!\1 XXXX!'
If your line isn't in a file, you can do it without sed :
var="DATE: 12 jan 2009, weather 20ºC"
echo "${var/DATE:*/DATE:xxxxx}"
You can use the shell
while IFS=":" read -r a b
do
case "$a" in
DATE* ) echo "$a:XXXX";;
*) echo "$a$b" ;;
esac
done < "file"
or awk
$ cat file
some line
DATE: 12 jan 2009, weather 20ºC
some line
$ awk -F":" '$1~/^DATE/{$2="XXXX"}1' OFS=":" file
some line
DATE:XXXX
some line
精彩评论