开发者

Bash substitution; remove everything after the string

开发者 https://www.devze.com 2022-12-22 08:43 出处:网络
This is probably a very stupid question, but in Bash I want to do the following substitution: I have in some files the line:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消